在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 字段
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
}
本文介绍了如何在EntityFrameworkCore中处理枚举类型的不便,通过新增一个不映射到数据库的枚举字段SendStateEnum,并提供转换逻辑,实现业务逻辑中对枚举的友好使用。同时,为了避免原字段SendState的误用,添加了[Obsolete]标记。这样,开发者可以安全地使用SendStateEnum进行查询和操作,提高代码可读性和维护性。
486

被折叠的 条评论
为什么被折叠?



