【问题标题】:How to map an enum property in Entity Framework 4如何在实体框架 4 中映射枚举属性
【发布时间】:2013-04-04 18:12:11
【问题描述】:

我的模型有一个枚举属性:

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 列不能为空。

如何让实体框架在保存/更新时将此属性转换为 Int,并在加载实体时将其转换为枚举。

【问题讨论】:

    标签: c# asp.net-mvc entity-framework asp.net-mvc-4


    【解决方案1】:

    Entity Framework 4 不支持使用枚举作为列类型。如果您想获得对枚举的原生支持,则需要升级到 Entity Framework 5。

    如果您绝对必须使用 EF 4(因为已经在其中实施了一个项目),那么我建议您这样做:

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

    这不是一个很好的解决方案,但它是解决问题的可靠解决方法,您仍然可以在您的页面上绑定它,并将其视为您其他代码中的枚举本身。

    【讨论】:

    • 请记住在查询中使用映射列var users = from q in Users where UserStatusAsInt == (int) UserStatus.Pending
    【解决方案2】:

    有时可能需要映射string 值而不是enumint 值。你可以这样做:

    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; }
        }
    }
    

    这实际上不是我的工作,我在尝试使用 EF4 映射 enums 时遇到。不幸的是,我不记得我在 SO 上找到它的地方了,不过仍然可能对其他人有用。

    【讨论】:

    • 你确定这对于多字枚举值也是可靠的吗?
    • 我没试过这样,所以我不能告诉你——虽然很有趣。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    相关资源
    最近更新 更多