9

我有这个架构:

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 创建类以映射它们?

4

1 回答 1

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");
        }); 
}
于 2011-02-26T17:38:05.950 回答