2016-11-22 94 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; } 
} 
相關問題