2013-04-24 80 views
0

如何爲EF構建這些表?EF多對多

第一個表:

public class model1 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Description { get; set; } 
} 

二表:具有第一和第二 和幾個字段的連接

public class model2 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Description { get; set; } 
} 

表:

public class model3 
{ 
    public int (id from model1){ get; set; } 
    public int (id from model2) { get; set; } 
    public int (id from model2){ get; set; } 
    public decimal Name{ get; set; } 
    public decimal Description{ get; set; } 
} 

回答

0

我認爲這可以做的伎倆(提供你所描述的表結構)

public class model3 
{ 
    public virtual model1 Model1 { get; set; } 
    public virtual model2 Model2 { get; set; } 
    public virtual model2 SecondModel2 { get; set; } 

    // if you want the ID fields explicitly, 
    // EF will map the keys by property name, 
    // optionaly you can use the ForeignKeyAttribute 
    public int Model1Id { get; set; } 
    public int Model2Id { get; set; } 
    public int SecondModel2Id { get; set; } 


    public decimal Name{ get; set; } 
    public decimal Description{ get; set; } 
} 

但是你可能要重新考慮結構 - 你提出的一個看起來有點可疑 - MODEL1和MODEL2具有相同的字段,所以也許他們不應該被定義爲單獨的類。 model3類也有一些共同的字段,所以也許值得將它們提取到一個普通的類中 - EF處理繼承。

爲了得到一個多對多的關係,不過,你需要的是這樣的:

public class Foo 
{ 
    public int Id {get;set;} 
    public virtual ICollection<Bar> Bars {get;set;} 
} 

public class Bar 
{ 
    public int Id {get;set;} 
    public virtual ICollection<Foo> Foos {get;set;} 
} 

這將創建一個Foo表,一個吧檯和一個FooBars(或BarFoos)associacion表。

+0

ok,並且對於model1和model2我必須添加公共虛擬ICollection Model3s {get;組; }? – user1600070 2013-04-24 12:36:21

+0

我的背景 public DbSet model1s {get;組; } public DbSet model2s {get;組; } public DbSet model3s {get;組; } 從我如何可以得到像context.model1s的東西。 (和SecondModel2Id的名稱) – user1600070 2013-04-24 12:44:20

+0

看看這個http://vincentlauzon.wordpress.com/2011/04/15/entity-framework-4-1-many-to-many-relationships-5/。多對多的關係在這裏詳細解釋 – Chris 2013-04-24 12:48:37