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

c# entity-framework entity-framework-core

Question

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?

1
1
11/22/2016 12:26:25 PM

Accepted 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>();
    }
}
1
11/23/2016 9:06:25 AM

Popular Answer

Using EF Code First you can do that like this

It is recommended to include foreign key property in an entity class. For example, if Foo entity includes FooPairId property which automatically becomes foreignkey property because it follows the convention for foreignkey < Type Name >Id.

Here you find tutorial

public class FooPair
{

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

public class Foo
{
    public Foo()
    {
        FooPairs = new List<FooPair>();
    }
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public int FooPairId { get; set; }
    [ForeignKey("FooPairId")]
    public ICollection<FooPair> FooPairs { get; set; }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow