
EntityFramework Coreのエンティティは列挙型操作を直接サポートしていないため、開発プロセスで多くのトラブルを引き起こします。以下にefコアで列挙を使用する方法をまとめます。
例えば、以下の MsgInfo エンティティは、データベーステーブル MsgInfo に対応し、フィールド SendState 送信ステータスは、ビジネスロジック上の2つの列挙ステータス *** send成功** と ** send失敗 *** を持つ。しかし、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 フィールドを追加した後、SendStateフィールドの代わりにef core 操作を使用するか、SendStateEnum を読み取ります(**注:ウェブマスターの測定値は元のテキストとは異なり、以下のコード(元のコード)のようにEF Core操作に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
}