5

我在保存數據庫中存在一些複雜關係的模型時遇到了一些麻煩。EF關係一對二

類的UML是: enter image description here

的類定義是:

public abstract class EntityBase 
{ 
    public virtual Guid Id { get; set; } 
} 

public class LoanRequest : EntityBase 
{ 
    [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public Guid Id { get; set; } 

    public virtual Applicant Applicant1 { get; set; } 
    public virtual Applicant Applicant2 { get; set; } 
} 

public class Applicant 
{ 
    [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public Guid Id { get; set; } 

    public Guid LoanRequestId { get; set; } 
    [ForeignKey("LoanRequestId")] 
    public virtual LoanRequest LoanRequest { get; set; } 

    public virtual ICollection<MonthlyIncome> Incomes { get; set; } 
} 

public class MonthlyIncome 
{ 
    [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public Guid Id { get; set; } 

    public Guid ApplicantId { get; set; } 
    [ForeignKey("ApplicantId")] 
    public virtual Applicant Applicant { get; set; }  
} 

我能夠運行由框架創建了遷移,並且尋找到數據庫中的表和列對我來說似乎很好。但是,當保存一個異常發生。例外情況是:

無法確定依賴操作的有效順序。由於外鍵約束,型號要求或商店生成的值,可能會存在依賴關係

我一直在尋找互聯網上的解決方案,我看不到我的問題在哪裏。有什麼建議麼?謝謝!

+0

什麼是你想保存?那麼保存方法是怎樣的呢? – janhartmann

回答

2

經過幾次嘗試,我找到了解決方案。申請人定義更改爲:

public class Applicant 
{ 
    [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public Guid Id { get; set; } 

    public virtual ICollection<MonthlyIncome> Incomes { get; set; } 
} 

是所有我需要