1

Reading this blog post about Primitive Obsession I was wondering:

  1. How can I create a strongly-typed entity using Entity Framework Code First? (specially regarding mapping these strong types to primitive types in SqlServer)

  2. Does that make sense? (I've never found any examples/tutorials on the web with this kind of approach)

Suppose we have an Address entity/class with a strongly-typed Zipcode property as we can see here.

brunosp86
  • 670
  • 1
  • 10
  • 21

1 Answers1

3

Edited version according to comment:

It make sense but you have never found any example because it is not directly possible with EF code first. Why?

  • Because EF doesn't support entities or complex types without default constructor and it cannot use constructor with parameters.
  • Because EF doesn't provide any type conversions so EF must map directly to primitive properties.
  • Because EF doesn't support properties without setter.

As a workaround you can use private setter and both default constructor (maybe it doesn't have to be public but I didn't try this) and constructor with parameters and correctly map property (at least with EDMX it works).

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • So, I removed the "readonly" keyword from the "_value" field and added a private set to the property "Value" in the Address class and now EF mapped as expected. Question is, how this changes violates the original ideia of primitive obsession? – brunosp86 Jan 05 '12 at 13:45
  • So my answer is wrong. I edited my answer to make it reference for others but you should put your solution to separate answer and accept it. – Ladislav Mrnka Jan 05 '12 at 14:18
  • The change slightly violates the pattern (for example it offers default constructor) but it is needed if you want to follow primitive type encapsulation with EF. – Ladislav Mrnka Jan 05 '12 at 14:24
  • The default constructor is also private – brunosp86 Jan 05 '12 at 14:58