我有2个型号:
public class TransactionHistory : IDbEntity {
[Key]
public int ID { get; set; }
public ItemHistory ItemHistory { get; set; }
}
public class ItemHistory : IDbEntity {
[Key]
public int ID { get; set; }
public int TransactionHistoryID { get; set; }
public TransactionHistory TransactionHistory { get; set; }
}
TransactionHistory和ItemHistory之间存在一对一的关系,ItemHistory必须有TransactionHistory,但TransactionHistory可能有也可能没有ItemHistory。
我希望能够在代码中执行此操作:
var test = db.ItemHistory.Include(x => x.TransactionHistory).ToList();
以及:
var test2 = db.TransactionHistory.Include(x => x.ItemHistory).ToList();
但我只想在ItemHistory表上使用一个FK。
使用我列出的代码,我收到此错误:
Unable to determine the principal end of an association between the types 'InventoryLibrary.DomainModels.TransactionHistory' and 'InventoryLibrary.DomainModels.ItemHistory'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
如何在Entity Framework代码中首先实现数据注释?
答案 0 :(得分:1)
首先,您必须按虚拟关键字标记外键以启用覆盖。
public class TransactionHistory : IDbEntity
{
[Key]
public int ID { get; set; }
public virtual ItemHistory ItemHistory { get; set; }
}
public class ItemHistory : IDbEntity
{
[Key]
public int ID { get; set; }
public int TransactionHistoryID { get; set; }
[Required]
public virtual TransactionHistory TransactionHistory { get; set; }
}
如果HistoryItem必须具有“事务历史记录”,请添加DataAnnotation [必需],这使其不可为空。
最后,想知道,如果你想建立一对一的关系。我想你想要有很多交易记录条目。我对吗?如果没有 - 让我知道。
要创建一对多关系,请使用IEnumerable<>类型。