[英]Entity Framework relations questions
我有三節課
public class SPR
{
public int ID { get; set; }
public string SubmittedBy { get; set; }
public virtual ICollection<SPRItem> AllItems { get; set; }
}
public class SPRItem
{
[Key]
public int ID { get; set; }
public string manufacturer { get; set; }
[ForeignKey("SPRItemDetails")]
public virtual SPRItemDetails ItemDetails { get; set; }
public string requestedMinimumQuantity { get; set; }
public virtual SPR SPR { get; set; }
}
public class SPRItemDetails
{
public int ID { get; set; }
public string ItemNumber { get; set; }
public virtual SPRItem SPRItem { get; set; }
}
所以SPR類有一個SPRItem集合,它有ItemDetails對象。
我有一個Web API方法,它將數據映射到SPR對象並填充SPRItem列表和ItemDetails對象。 但每當我嘗試使用Entity Framework代碼保存它時,我就會收到此錯誤
{"Message":"An error has occurred.","ExceptionMessage":"Unable to determine the principal end of an association between the types 'SharePoint.MultiSPR.Service.Models.SPRItemDetails' and 'SharePoint.MultiSPR.Service.Models.SPRItem'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
這是我的背景
public System.Data.Entity.DbSet<SharePoint.MultiSPR.Service.Models.SPR> SPRs { get; set; }
public System.Data.Entity.DbSet<SharePoint.MultiSPR.Service.Models.SPRItem> SPRItem { get; set; }
public System.Data.Entity.DbSet<SharePoint.MultiSPR.Service.Models.SPRItemDetails> SPRItemDetails { get; set; }
有人可以告訴我如何正確配置關系。
謝謝
在1:1關系中,您始終必須指明委托人和從屬實體。 主要實體是最獨立於另一個實體的實體,在這種情況下可能是SPRItem
。
接下來要決定的是關系應該是可選的還是必需的。 我認為,根據實體名稱判斷,如果沒有SPRItem
, SPRItemDetails
將永遠不存在,因此關系為1:0..1
(不是0..1:0..1
)。 以下是配置:
modelBuilder.Entity<SPRItem>()
.HasOptional(si => si.ItemDetails)
.WithRequired(id => id.SPRItem);
這創建(或要求)具有主鍵的SPRItemDetails
表,該主鍵也是SPRItem
的外鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.