如何使用与EF4 Code First相同的表做多对多

Omu*_*Omu 9 entity-framework code-first entity-framework-4 ef-code-first entity-framework-ctp5

我有这个架构:

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

create table PersonPersons
(
PersonId references Person(id),
ChildPersonId references Person(id)
)
Run Code Online (Sandbox Code Playgroud)

如何创建使用EF4 Code First CTP5映射它们的类?

Bri*_*ler 10

对于POCO ......

class Person
{
    public Guid PersonId { get; set; }
    public virtual Person Parent { get; set; }
    public virtual ICollection<Person> Children { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

...在DbContext中设置映射...

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

...将为您提供默认实现.如果您需要显式重命名表(并希望获得多对多关系),请添加类似这样的内容......

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");
        }); 
}
Run Code Online (Sandbox Code Playgroud)

  • 注意:在EF 5.0中,只需将`map.MapLeftKey(left => left.PersonId,"PersonId")更改为`map.MapLeftKey("PersonId");`,并为右键更改`. (2认同)