2016-11-22 98 views
1

我要地图是这样的:两个一比一的关系对实体框架的核心同桌

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

而且我的DbContext:

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

EF抱怨它无法确定由Parent导航属性表示的关系。

我能想到的唯一解决方案是创建两个新的继承类fhm Foo,然后EF将它们映射到他们自己的表格,并且我得到两个1对1的关系,但这并不正确。

什么是建模这种情况的正确方法?

+0

你为什么要使用两个单对单的关系在一个表上?我不了解情况。你可以使用一对多的关系和你的代码方面的手动限制我是对的吗? – kizilsu

+0

@kizilsu是的,这就是我需要的。但是因为我对EF很陌生,所以我决定问一下,因为也许有一种方法可以通过模式限制这一点,那么我就不需要在代码中担心它了。 – RBasniak

回答

1

我想下面的代码帮助解决你的问题。 参考Eftutorials了解更多详情。

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

使用EF代码首先,你可以是这样做的

建议包括实体类中的外键属性。 例如,如果Foo实体包括FooPairId属性, 自动成为外键属性,因为它遵循 约定的外键<类型名称>标识。

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; } 
} 
相关问题