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.
2 Answers 2
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.
-
3Just remember to use the mapped column in your queries:
var users = from q in Users where UserStatusAsInt == (int) UserStatus.Pending
Branco Medeiros– Branco Medeiros2013年04月04日 19:11:27 +00:00Commented Apr 4, 2013 at 19:11
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.
-
Are you sure that this would be reliable for multi-word enum values as well?Corey Adler– Corey Adler2013年04月05日 18:16:45 +00:00Commented Apr 5, 2013 at 18:16
-
I haven't tried it with such so I couldn't tell you - interesting though.MattSull– MattSull2013年04月06日 11:12:03 +00:00Commented Apr 6, 2013 at 11:12
Explore related questions
See similar questions with these tags.