2017-04-25 82 views
0

我遇到了2個實體之間的關係問題;INSERT語句與FOREIGN KEY約束衝突 - 實體框架

我的課程如下;

public class Cis 
{ 
    [Key] 
    public int CisId { get; set; } 
    public int ProjectId { get; set; } 

    [ForeignKey("ProjectId")] 
    public virtual ICollection<Overhead> Overheads { get; set; } 

} 

public class Overhead 
{ 
    public int Id { get; set; }  
    public int ProjectId { get; set; } 
    public SecuredWorkType SecuredWorkType { get; set; } 
    public decimal? OverheadRecoveryTotalValue { get; set; } 
    public decimal? BudgetedFinancialResultValue { get; set; } 
    public decimal? SecuredValue { get; set; } 
    public decimal? OverheadRecoveryTotalPercentage { get; set; } 
} 

當我試圖保存多個開銷的CIS對象就可以了,我得到以下錯誤

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Overhead_dbo.Cis_ProjectId". The conflict occurred in database "CisLatest", table "dbo.Cis", column 'CisId'.The statement has been terminated." 

我不能用在獨聯體CisId如因設計關注我的外鍵 - 當我使用CisId作爲外鍵時,它工作正常。

我在這裏看過類似的問題和答案,雖然他們顯示把父實體放在孩子裏面?不知道這是否適用於這種情況

感謝您的幫助。

+0

1'ProjectId'。 2.這裏真正的關係是什麼?要使''[ForeignKey(「ProjectId」)]'工作,您需要在'Overhead'中設置[Key]' –

+0

應用程序結構是;一個項目,其中有許多Cis的,並有許多開銷。現在我正在考慮這個問題,考慮到這一點,不需要在CIS和開銷之間建立直接關係,因爲開銷是每個項目而不是Cis,這可能是我感到困惑的地方。 – Aeptitude

+1

看起來你需要重新考慮你的數據結構。就他而言,我認爲,你需要:'項目','Cis','Overhead','Project_Cis','Project_Overhead'。突然,看起來像你可以建立你的EDM –

回答

0

嘗試在兩個模型

public class Cis 
{ 
    [Key] 
    public int CisId { get; set; } 
    [ForeignKey("ProjectId")] //here 
    public int ProjectId { get; set; } 


    public virtual ICollection<Overhead> Overheads { get; set; } 

} 
+0

感謝您的回覆,沒有好的恐懼 - 當我嘗試使用Cis類中projectId上方的外鍵屬性進行遷移時出現此錯誤; 「屬性'ProjectId'不能被配置爲導航屬性,屬性必須是有效的實體類型,屬性應該有一個非抽象的getter和setter對於集合屬性,類型必須實現ICollection 其中T是一個有效的實體類型。」 – Aeptitude

相關問題