1

I am using POCOs (no proxies) with EF4.

In the database, I have this nullable decimal column:

<Property Name="AMOUNT" Type="decimal" Precision="12" Scale="2" />

On my POCO, I have this non-nullable value property:

public decimal Amount { get; set; }

If the value in the database is null, I want the property to be set to 0. How can I achieve this? I would prefer not to have a Nullable property here, otherwise I have to pollute my business logic with GetValueOrDefault() code.

[This question seemed like what I was asking, but I'm not sure it was really answered.]

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Ben Vitale
  • 1,754
  • 3
  • 17
  • 27

1 Answers1

2

Unfortunately you must use nullable decimal in your POCO because EF doesn't provide any simple type mapping / type converters where you could place your transformation logic. Types must be same to make it work.

In case of EDMX there is one possible ugly workaround. You can map your column to non public property and expose another public property which will be not mapped (in your partial part of POCO class) and you will have your conversion logic in its getter and setter. Here is described how you can change visibility of property.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • "In case of EDMX there is one possible ugly workaround." - this is not an ugly workaround, but a common practice. Entity framework has many limitations and class files are intentionally generated as partial so that you can add whatever you want to them. By the way - creating pure data classes (without any logic - like those generated by EF) is an anti pattern. – kubal5003 Jul 18 '11 at 20:53
  • @kubal: That is workaround because this mapping logic should be part of ORM itself. Also your anti pattern exists only in the world of domain driven design and it is called anemic domain model. If you don't follow domain driven design you don't have that anti pattern. – Ladislav Mrnka Jul 18 '11 at 21:07
  • You're right, my point was that since EF intentionally supports partial classes that cannot be considered as ugly, but if you look at the whole design then this for sure is not the elegant way of doing things. – kubal5003 Jul 18 '11 at 21:46
  • I'm doing Domain Driven Design and my POCOs were created manually beforehand. Since I'm trying to maintain persistence ignorance, it pains me slightly that I need to implement some special logic in my POCO just so that my public Amount property can be non-nullable - in the EF world. I have another persistence layer I'm trying to support that can do the conversion before it calls the setter. Either way, I can probably live with this - your answer is what I was expecting, so thanks. – Ben Vitale Jul 20 '11 at 12:56