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

时间:2011-02-24 09:50:53

标签: entity-framework entity-framework-4 code-first entity-framework-ctp5 ef-code-first

我有这个架构:

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

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

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

1 个答案:

答案 0 :(得分: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");
        }); 
}