Reputation: 4954
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?
Upvotes: 3
Views: 2327
Reputation: 1041
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>();
}
}
Upvotes: 1
Reputation: 6203
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.
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; }
}
Upvotes: 2