Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map an enum property in Entity Framework 4

My model has a property that is an enumeration:

Sql server column "user_status" is a int NOT NULL.

[Column("User_Status")]
public UserStatus UserStatus { get; set; }

public enum UserStatus
{
    Pending  = 1,
    Member = 2,
    Banned   = 3
}

Currently I am getting an error when I save the entity because it says the column user_status cannot be null.

How can I get entity framework to convert this property to an Int when it saves/updates, and when it loads the entity it converts it to the enum.

like image 618
loyalflow Avatar asked Dec 06 '22 08:12

loyalflow


2 Answers

Entity Framework 4 does not support using enums as column types. If you want to have native support for enums, you'll need to upgrade to Entity Framework 5.

If you absolutely have to use EF 4 (because of a project that's already been implemented in it), then I recommend that you go around it as so:

[Column("User_Status")]
public int UserStatusAsInt { get; set; }

[NotMapped]
public UserStatus UserStatus
{
  get { return (UserStatus) this.UserStatusAsInt; }
  set { this.UserStatusAsInt = (int)value; }
}

It's not a pretty solution, but it's a solid workaround to the problem, and you still get to bind to it on your pages and treat it as the enum itself in your other code.

like image 190
Corey Adler Avatar answered Dec 25 '22 16:12

Corey Adler


Sometimes it can be desirable to map the string value and not the int value of the enum. You can do it like this:

public enum DwellingType { Apartment, Cottage, House }

public DwellingType DwellingType { get; set; } // This wont be mapped in EF4 as it's an enum

public virtual string DwellingTypeString       // This will be mapped
{
    get { return DwellingType.ToString(); }
    set
    {
        DwellingType stringValue;
        if(Enum.TryParse(value, out stringValue))
        { DwellingType = stringValue; }
    }
}

This isn't actually my work, I came across while trying to map enums with EF4. Unfortunately I can't remember where I found it on SO, still might be useful to others though.

like image 44
MattSull Avatar answered Dec 25 '22 16:12

MattSull