在EntityFramework Core中的实体是不直接支持枚举类型的操作,这让我们在开发过程中带来不少的麻烦,下面总结一下在ef core中使用枚举的方法.

例如下面的MsgInfo实体,对应着数据库表MsgInfo,其中字段SendState发送状态在业务逻辑上有发送成功发送失败两种枚举状态。但ef把它生成了int类型,而不是枚举,当然也不能修改成枚举,这样会导致ef写入和读取数据异常。

原来的实体

public partial class MsgInfo
{
    public string Id { get; set; }
    public string UserAddress { get; set; }
    public string Content { get; set; }
    public int SendState { get; set; }
}

这里新增一个字段SendStateEnum设置为枚举类型,并使用 [NotMapped] 为不映射到数据库,为了防止输出HTTP时被序列化,也可以添加 [Newtonsoft.Json.JsonIgnore] 标记

需添加Nuget包Newtonsoft.Json

修改完的实体代码如下

修改实体

public partial class MsgInfo
{
    public string Id { get; set; }
    public string UserAddress { get; set; }
    public string Content { get; set; }
    public int SendState { get; set; }

    [NotMapped]
    [Newtonsoft.Json.JsonIgnore]
    public SendStateEnum SendStateEnum
    {
        get
        {
            switch (SendState)
            {
                case (int)SendStateEnum.Fail:
                    return SendStateEnum.Fail;
                case (int)SendStateEnum.Success:
                    return SendStateEnum.Success;
                default:
                    return SendStateEnum.UnKnow;
            }
        }
        set
        {
            SendState = (int)value;
        }

    }
}
public enum SendStateEnum
{
    Success = 1,
    Fail = 2,
    UnKnow =3 
}

添加了SendStateEnum字段后,以后使用ef core操作或者读取SendStateEnum 代替了 SendState 字段(注:站长实测与原文有出入,如下面的代码(原文代码)貌似应该使用SendState进行EF Core的操作,如有不同意见请留言指正。

using (var context = new FrameworkDbContext())
{
    var result = context.MsgInfo.Where(m => m.SendStateEnum == SendStateEnum.Success);
}

当然,为了防止原来的 SendState 字段被使用,可以添加标记 [Obsolete] 提醒用户该字段 SendState 已过时。

修改后的最终实体代码如下

public partial class MsgInfo
{
    public string Id { get; set; }
    public string UserAddress { get; set; }
    public string Content { get; set; }

    [Obsolete]
    public int SendState { get; set; }

    [NotMapped]
    [Newtonsoft.Json.JsonIgnore]
    public SendStateEnum SendStateEnum
    {
        get
        {
            switch (SendState)
            {
                case (int)SendStateEnum.Fail:
                    return SendStateEnum.Fail;
                case (int)SendStateEnum.Success:
                    return SendStateEnum.Success;
                default:
                    return SendStateEnum.UnKnow;
            }
        }
        set
        {
            SendState = (int)value;
        } 
    }
}
public enum SendStateEnum
{
    Success = 1,
    Fail = 2,
    UnKnow =3 
}