【问题标题】:how to do many to many with the same table with EF4 Code First如何使用 EF4 Code First 对同一张表进行多对多操作
【发布时间】:2011-07-03 10:35:51
【问题描述】:

我有这个架构:

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

【问题讨论】:

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


【解决方案1】:

对于 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");
        }); 
}

【讨论】:

  • 我在哪里将 .Map(map => 与其他所有内容连接起来?
  • 在上面编辑以显示带有 .Map() 的 MTM 配置。我想也可能有一种方法可以直接定义 Person 和 PersonPersons POCO。
  • 注意:在 EF 5.0 中,只需将 map.MapLeftKey(left =&gt; left.PersonId, "PersonId"); 更改为 map.MapLeftKey("PersonId");,并使用正确的键。
  • 我使用了这种设计,然后我发现该表会阻止您删除实体。太棒了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多