ADO.NET.EF.&.Enums

While migrating my LayerSample to ADO.NET Entity Framework (EF), I have discovered some limitations and restrictions with ADO.NET EF. One of them is that ADO.NET EF does not seem to support enums. Unlike LINQ-to-SQL where we can change the type of a property to map to an enum, the model designer that comes with EF does not permit it. Furthermore, any attempt to change the generated code will result in the changes being discarded when we save and compile the project.

Fortunately, there is workaround for this. We can substitute the original non-enum property with a new property using an enum type in a partial class. For example, let's take a look at the ExpenseLog class that was generated by EF. There is a StatusID property of the type Byte that should be exposed as an ExpenseStatus Enum.

This can be achieved by first hiding the StatusID property from its callers by setting the Getter and Setter of the property to Private.

Next, create a partial class and declare a new property as follows:

public ExpenseStatus Status
{
get { return (ExpenseStatus)this.StatusID; }
set { this.StatusID = (byte?)value; }
}

That's it! Now we can use the Status property in place of the StatusID property.

No comments:

Post a Comment

Popular Post