我正在使用这样的枚举类:
public class BillTransactionState
{
public static readonly BillTransactionState Initialized = new BillTransactionState(1, "Initialized");
public static readonly BillTransactionState Invoiceable = new BillTransactionState(2, "Invoiceable");
public static readonly BillTransactionState NoSow = new BillTransactionState(3, "NoSow");
public static readonly BillTransactionState Invoiced = new BillTransactionState(4, "Invoiced");
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
我还有另一个引用BillTransactionState的类:
public class BillTransactionStateHistory : IEntity<long>
{
public long Id { get; set; }
public DateTime EffectiveDate { get; set; }
public BillTransactionState BillTransactionState { get; set; }
}
在我的webapi中,当我执行以下操作时:
var billTransactionStateHistory = new BillTransactionStateHistory ({
BillTransaction = BillTransaction .Initialized,
EffectiveDate = DateTime.Now
});
_dbContext.BillTransactionStateHistories.AddAsync(billTransactionStateHistory)
我得到一个错误:
BillTransactionState的身份插入无效。
我意识到EF Core试图在BillTransactionState表中插入值为1(对于Id)和'Initliazed'的行。如何阻止EF Core尝试在此枚举类中插入一行。任何对此的帮助将不胜感激。谢谢。
答案 0 :(得分:0)
编写您的BillTransactionStateHistory
模型类,如下所示:
public class BillTransactionStateHistory : IEntity<long>
{
public long Id { get; set; }
public DateTime EffectiveDate { get; set; }
public int BillTransactionState { get; set; }
}
注意:之后,别忘了相应地更新数据库!
然后使用Web API方法:
var billTransactionStateHistory = new BillTransactionStateHistory ()
{
BillTransactionState = BillTransactionState.Initialized.Id,
EffectiveDate = DateTime.Now
};
_dbContext.BillTransactionStateHistories.AddAsync(billTransactionStateHistory)
答案 1 :(得分:0)
您可以在官方的EF Core GitHub存储库上看到this的答案。
您的枚举类和实体类将保持不变。您将必须引入ValueConverter
或使用PropertyBuilder.HasConverter
来提供与BillTransactionState
和int
之间的映射。
Lambda示例:
// builder is IEntityTypeConfiguration<BillTransactionStateHistory>
builder.Property(e => e.BillTransactionState)
.HasColumnName("state")
.HasConversion(state => state.Id, stateId => SomeLookupMethod(stateId));
public BillTransactionState SomeLookupMethod(int id)
{
// TODO: Lookup transaction state based on id.
}
请注意,EF Core 2.x的问题在于值转换器和lambda不能正确映射到查询表达式。 EF Core 3.x已修复此(related issue)