[英]Entity Framework populating wrong column with Foreign Key
我試圖建立一對一關系,但是當我創建數據時,EF將外鍵設置為另一列。 請在下面的課程中查看:
public class SWAChecklist
{
public SWAChecklist()
{
this.Steps = new Steps() { SWAChecklist = this };
this.Observers = new List<Observer>();
this.PersonnelObserved = new List<PersonObserved>();
this.JobFactors = new JobFactors() { SWAChecklist = this };
this.Causes = new Causes() { SWAChecklist = this };
this.Hazards = new Hazards() { SWAChecklist = this };
}
public int ID { get; set; }
public string Status { get; set; }
public string Job { get; set; }
public Causes Causes { get; set; }
}
public class Causes
{
[Key]
public int? ID { get; set; }
public int SWAChecklistId { get; set; }
[Required]
public virtual SWAChecklist SWAChecklist { get; set; }
public bool? AdditionalHazard { get; set; }
public bool? UnsafeBehavior{ get; set; }
public bool? Planned { get; set; }
}
因此,當我嘗試創建SWAChecklist.Causes時,它會將檢查清單的ID分配給原因上的ID列,而不是SWAChecklistId。 謝謝你的幫助。
讓我們假設EF將允許您在依賴方與ID
和SWAChecklistId
兩者建立1:0..1關系。 為了避免SWAChecklistId
關系,EF在SWAChecklistId
上需要一個UNIQUE約束。 然后,您將擁有SWAChecklistId
,這是唯一的(外來)鑰匙欄-這是對主鑰匙的完美描述。
因此,對於1:0..1關系,使用與主鍵和外鍵相同的列是一個不錯的設計決策,EF緊隨其后。
如果(出於任何原因)需要單獨的外鍵,則可以配置1:many關系並在外鍵上創建唯一索引,以有效地將“ many”限制為0..1。
public class SWAChecklist
{
public SWAChecklist()
{
this.Steps = new Steps() { SWAChecklist = this };
this.Observers = new List<Observer>();
this.PersonnelObserved = new List<PersonObserved>();
this.JobFactors = new JobFactors() { SWAChecklist = this };
this.Causes = new Causes() { SWAChecklist = this };
this.Hazards = new Hazards() { SWAChecklist = this };
}
[Key]
public int ID { get; set; }
public string Status { get; set; }
public string Job { get; set; }
public virtual Causes Causes { get; set; }
}
public class Causes
{
[Key]
[ForeignKey("SWAChecklist")]
public int ID { get; set; }
[Required]
public bool? AdditionalHazard { get; set; }
public bool? UnsafeBehavior{ get; set; }
public bool? Planned { get; set; }
public virtual SWAChecklist SWAChecklist { get; set; }
}
你可以試試
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.