9

我有这样的模式:怎么办多对多与同桌EF4代码优先

create table Person 
(
id int identity primary key, 
name nvarchar(30) 
) 

create table PersonPersons 
(
PersonId references Person(id), 
ChildPersonId references Person(id) 
) 

如何使用EF4代码优先CTP5创建类映射呢?

+0

可能重复引用许多一对多](http://stackoverflow.com/questions/4981228/entity-framework-4-ctp-5-self-referencing-many-to-many) – 2011-02-24 10:04:22

回答

10

对于POCO ...

class Person 
{ 
    public Guid PersonId { get; set; } 
    public virtual Person Parent { get; set; } 
    public virtual ICollection<Person> Children { get; set; } 
} 

......设立在的DbContext的映射......

protected override void OnModelCreating(ModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<Person>() 
     .HasOptional(entity => entity.Parent) 
      .WithMany(parent => parent.Children) 
      .HasForeignKey(parent => parent.PersonId); 
} 

...会给你一个默认的实现。如果您需要重命名明确表(并希望多到许多关系),加入这样的事情...

class Person 
{ 
    public Guid PersonId { get; set; } 
    public virtual ICollection<Person> Parent { get; set; } 
    public virtual ICollection<Person> Children { get; set; } 
} 

protected override void OnModelCreating(ModelBuilder modelBuilder) 
{ 
    ConfigureProducts(modelBuilder); 
    ConfigureMembership(modelBuilder); 

    modelBuilder.Entity<Person>() 
     .HasMany(entity => entity.Children) 
     .WithMany(child => child.Parent) 
     .Map(map => 
     { 
      map.ToTable("PersonPersons"); 
      map.MapLeftKey(left => left.PersonId, "PersonId"); 
      map.MapRightKey(right => right.PersonId, "ChildPersonId"); 
      // For EF5, comment the two above lines and uncomment the two below lines. 
      // map.MapLeftKey("PersonId"); 
      // map.MapRightKey("ChildPersonId"); 
     }); 
} 
[实体框架4 CTP 5自我
+0

我在哪里连接.Map(map =>与其他所有内容? – Omu 2011-02-28 08:30:54

+0

上面编辑,用.Map()显示MTM配置,我想可能有一种方法可以直接定义一个Person和一个PersonPersons POCO – 2011-03-01 04:15:02

+2

注意:在EF 5.0中,只需改变'map.MapLeftKey(left => left .PersonId,“PersonId”);'到'map.MapLeftKey(“PersonId”);',并且这样做是为了正确的钥匙 – deerchao 2013-05-15 07:54:10