实体框架代码第一个多父映射

时间:2013-10-12 09:08:13

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

我试图在EF 4.3中创建这三个模型:

 - Family
  - Guid FamilyId
  - ICollection< Person> Members
 - Company
  - Guid CompanyId
  - ICollection< Person> Employees
 - Person
  - Guid PersonId
  - String Name

A person can belong to multiple families and multiple companies, as well as doesn't belong to any.

运行代码后,数据库中的映射似乎有点奇怪。未映射家庭成员和公司 - 员工。此外,Persons表中有四列:PersonId,Name,Family_FamilyId和Company_CompanyId。

我认为我的代码意味着一个人将永远属于1个家庭和1个公司。我该如何更改代码?

2 个答案:

答案 0 :(得分:1)

您不能在课程中表达所有这些信息。要添加额外信息,您可以选择几个选项。

您可以将其添加到您的EF上下文类

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{ 
    //All people must belong to a family.
    modelBuilder.Entity<Family>().HasMany(x => x.Members)
           .WithRequired();

    //Each person may belong to ZERO-Many companies.
    modelBuilder.Entity<Company>().HasMany(x => x.Employees)
           .WithMany();        
}

或者这是你的EF上下文类

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{ 
    modelBuilder.Configurations.Add(new ComapnyMapper());
    modelBuilder.Configurations.Add(new FamilyMapper());

}

public class FamilyMapper : EntityTypeConfiguration<Family>
{
     public FamilyMapper()
     {
          HasMany(x => x.Members)
           .WithRequired();        
     }
}
public class CompanyMapper : EntityTypeConfiguration<Company>
{
     public CompanyMapper()
     {
          HasMany(x => x.Employees)
           .WithMany();        
     }
}

答案 1 :(得分:0)

我最终将模型类更改为

  • 家庭
    • Guid FamilyId
    • 的ICollection&LT;人&GT;成员
  • 公司
    • Guid CompanyId
    • 的ICollection&LT;人&GT;员工
    • Guid PersonId
    • 字符串名称
    • 的ICollection&LT;家庭&GT;家庭
    • 的ICollection&LT;公司&GT;公司