RBasniak RBasniak - 10 days ago 7
C# Question

Two one-to-one relations to the same table on Entity Framework Core

I would like to map something like this:

public class FooPair
{
public int Id { get; set; }
public Foo Foo1 { get; set; }
public Foo Foo2 { get; set; }
}

public class Foo
{
public int Id { get; set; }
public FooPair Parent { get; set; }
}


And my DbContext:

public class FooContext : DbContext
{
public DbSet<Foo> Foos { get; set; }
public DbSet<FooPair> Pairs { get; set; }
}


EF is complaining it's unable to determine the relationship represented by the
Parent
navigation property.

The only solution I could think of, is to create two new inherited classes fom
Foo
, then EF will map them to their own tables and I get two 1-to-1 relations, but this doesn't feel right.

What would be the correct way of modeling such situation?

Answer

I think below code help to solve your problem. refer Eftutorials for more details.

public class Foo
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public virtual FooPair FooPair { get; set; }
}

public class FooPair
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int Id { get; set; }   
   public virtual ICollection<Foo> Foos { get; set; }

   public Foo()
    {
        Foos = new List<Foo>();
    }
}
Comments