1

In a legacy database, NULL values are sometimes stored as the string NULL and/or "x".

How can I tell EF that I want it to automatically convert those "placeholder values" to NULL?

Update:
I want to avoid ambiguity / accidental complexity in my model by having the same property twice. (If people can get/set LegacyColumn, they will and abstraction is broken)

Laoujin
  • 9,962
  • 7
  • 42
  • 69

1 Answers1

3

You can create a new property based on the existing property that is not mapped to the database and that performs the desired conversion. Assuming the column is named Foo you can use this code:

[Column("Foo")]
public String FooWithWeirdNullValues { get; set; }

[NotMapped]
public String Foo {
  get {
    return FooWithWeirdNullValues == "NULL" || FooWithWeirdNullValues == "x"
      ? null : FooWithWeirdNullValues;
  }
  set { FooWithWeirdNullValues = value; }
}

In your code you then use the unmapped property to access the value of the Foo column.

You might want to pick another name for FooWithWeirdNullValues e.g. LegacyFoo or whatever. You can pick any name as long as you use the Column attribute to map it to the correct column in the database.

If desired you can make FooWithWeirdNullValues private to not pollute your model. This requires a few changes to the DbContext as described in an answer on Stack Overflow on how to map private properties using code first.

Community
  • 1
  • 1
Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
  • This would pollute my model :(. In NHibernate this can be achieved quite easily, I'm surprised EF does not have this? I was hoping `EditorBrowsable(Never)` would solve that but it doesn't. – Laoujin Feb 12 '15 at 13:20
  • @Laoujin: I have updated my answer with some additional information that might address your concern about polluting the model. – Martin Liversage Feb 12 '15 at 14:00