2013-04-24 81 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