2017-08-10 20 views
0

我試圖建立一對一的關係,但是當我創建數據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,它被賦予的,而不是SWAChecklistId清單上的原因列ID的ID。 感謝您的幫助。

回答

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; } 
} 

,您可以嘗試

2

讓假設EF將允許你建立一個1:對因側兩者IDSWAChecklistId 0..1關係。爲了避免1:多關係,EF在SWAChecklistId上需要一個UNIQUE約束。那麼你將有SWAChecklistId,一個獨特的(外國)鍵列 - 這是一個主鍵的完美描述。

因此,使用與主鍵和外鍵相同的列對於1:0..1關係是一個很好的設計決策,並且EF在跟隨它。

如果你(出於任何原因)需要一個單獨的外鍵,您可以配置1:許多關係和外鍵創建唯一索引,以有效地限制了「許多」,以0..1

+0

謝謝男人,這很有道理。 :) –