Blog from Saravanan Arumugam

Let us talk about Technologies

Enums in Entity framework


I had a need of using an Enum in one of the entities I created in Visual Studio 2010. Eventually I figured out that there’s no direct support to Enum in Entity framework 4.0. However there are workarounds to bring the Enum in place.

If we google, we can find out some of the workarounds to use the Enum.

Solution

Here’s a simple method I came up with to use the Enum, in an entity.

If we open Entities.Designer.cs file, we can find that the files are partials.

    [EdmEntityTypeAttribute(NamespaceName="MyModel", Name="ICFile")]
    [Serializable()]
    [DataContractAttribute(IsReference=true)]
    public partial class ICFile : EntityObject

Step 1: To support enum, create an enum.

    public enum FileStatus
    {         InProgress = 0,         Error = 1,         Completed = 2
    }

Step 2: In the namespace of the Entities, create a partial class as the entity you want to expand.

    public partial class ICFile
    {                 [DataMemberAttribute()]         public FileStatus FileStatus         {             get
            {                 return (FileStatus)this.Status;             }             set
            {                 this.Status = (int)value;             }         }     }

Step 3: Create a full property that’ll uses the existing property of the entity but wraps it with the enum we created as in the above example.

So from now on, the new property (FileStatus) would be available in the entity for any kind of statements we use.

context.AddToICFiles(     new ICFile
    {         FileName = FileName,         FileStatus = FileStatus.InProgress     });

However, this property wouldn’t be available/supported any linq statements. (Or perhaps I haven’t figured that out).

var fileEntry = (from entry in context.ICFiles
    where entry.FileName == FileName &&
        //Following statment is not supported by the linq to entity, 
        //since and Edm property has to be marked as EmdPropertyAttribute. 
        //But FileStatus is not marked with an attribute.
        //entry.FileStatus == FileStatus.InProgress && 
 
        //This would work well.
        entry.Status == (int)FileStatus.InProgress
    select entry).First();

The code above explains what’s not supported and how to solve it.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: