How do I translate null values from database to DbSet and back in Entity Framework?

entity-framework entity-framework-6

Question

I have a database that has been used to store nullable ThingType? enum as integer values:

public enum ThingType
{
    Good = 0,
    Bad = 1,
    Annoying = 2,
}

But that has meant custom code to accommodate null values elsewhere in my project. I want to modify my enum to have a "Not Specified" value for ThingType, as defined below:

public enum ThingType
{
    NotSpecified = -1,
    Good = 0,
    Bad = 1,
    Annoying = 2,
}

What's the best way to implement this translation in EF without making changes to the database, so that null row values are translated to ThingType.NotSpecified and ThingType.NotSpecified is inserted as a null value?

1
1
1/28/2019 9:01:24 PM

Popular Answer

Use a second property

// Map this one to DB
public ThingType? ThingTypeDb
{
    get { return ThingType == ThingType.NotSpecified ? (ThingType?)null : ThingType; }
    set { ThingType = value == null ? ThingType.NotSpecified : value.Value; }
}

// Don't map this one. Use it in your logic
public ThingType ThingType { get; set; }
0
1/28/2019 9:24:32 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow