c# - EF关系一对二

标签 c# asp.net-mvc entity-framework foreign-keys data-annotations

我在数据库中保存一个关系有点复杂的模型时遇到了一些麻烦。

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

我能够运行迁移并查看数据库,框架创建的表和列对我来说似乎没问题。但是,保存时发生异常。异常(exception)情况是:

Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values

我一直在互联网上寻找解决方案,但看不出我的问题出在哪里。有什么建议么?谢谢!

最佳答案

经过多次尝试,我找到了解决方案。将申请人定义更改为:

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

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

是我所需要的

关于c# - EF关系一对二,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35017206/

相关文章:

c# - Entity Framework 已经有一个打开的 DataReader 与此命令关联,必须先将其关闭

c# - 如何在不同的可执行文件之间共享或保存数据?

使用列表的 C# 递归编程

c# - ManyToOne 约束不起作用

c# - 将 mongodb 连接到 C#

performance - 为什么DbSet.Add工作这么慢?

c# - 使用扩展方法 (EF5) 恢复 DbContext.Detach() 方法

c# - 数据绑定(bind)不适用于 Avalondock 窗口

c# - 尝试在 ASP.NET MVC 应用程序中打开 db4o 数据库时,是什么导致此 DatabaseFileLockedException?

asp.net - ASP.NET MVC 中请求的日期 header