如何枚举属性实体框架图4 [英] 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
}
目前,我得到一个错误,当我保存实体,因为它说,该列user_status不能为null。
Currently I am getting an error when I save the entity because it says the column user_status cannot be null.
我怎样才能得到实体框架时,它保存/更新此属性转换为int,而当它加载的实体将它转换为枚举。
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.
推荐答案
实体框架4不支持使用枚举列类型。如果你想为枚举的原生支持,你需要升级到实体框架5。
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.
如果你绝对必须使用(因为这是已经在实施了一个项目)EF 4,那么我建议你围绕它去像这样:
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; }
}
这不是一个pretty的解决方案,但它是一个坚实的解决方法的问题,你仍然可以绑定到它在您的网页,并把它作为枚举本身在其他code
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.
这篇关于如何枚举属性实体框架图4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!