Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF relation one-to-two

I'm having some troubles when saving in the database a model with a little complex relationship.

The UML of the classes is: enter image description here

The classes definition are:

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

I'm able to run a migration and looking into the database the tables and columns created by the framework seems fine to me. But, when saving an exception happens. The exception is:

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

I've been searching for a solution on the internet and I can't see where my problem is. Any suggestions? Thanks!

like image 333
joacoleza Avatar asked Oct 30 '22 10:10

joacoleza


1 Answers

After several tryings I was able to find a solution. Changing the applicant definition to:

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

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

was all I needed

like image 104
joacoleza Avatar answered Nov 09 '22 07:11

joacoleza