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.

asked Apr 4, 2013 at 18:12
0

2 Answers 2

13

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.

answered Apr 4, 2013 at 18:17
1
  • 3
    Just remember to use the mapped column in your queries: var users = from q in Users where UserStatusAsInt == (int) UserStatus.Pending Commented Apr 4, 2013 at 19:11
2

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.

answered Apr 4, 2013 at 23:07
2
  • Are you sure that this would be reliable for multi-word enum values as well? Commented Apr 5, 2013 at 18:16
  • I haven't tried it with such so I couldn't tell you - interesting though. Commented Apr 6, 2013 at 11:12

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.