配置实体之间的多个关系

时间:2012-01-10 09:31:08

标签: c# entity-framework ef-code-first

我有PersonCourse实体有多种关系:

public class Course
{
    public int CourseID { get; set; }
    public virtual Person Leader { get; set; }
    public virtual ICollection<Person> Teachers { get; set; }
    public virtual Person CreatedBy { get; set; }
    public virtual Person UpdatedBy { get; set; }
    ...
}

public class Person
{
    public int PersonID { get; set; }
    public virtual ICollection<Course> CoursesCreated { get; set; }
    public virtual ICollection<Course> CoursesUpdated { get; set; }
    public virtual ICollection<Course> CoursesLead { get; set; }
    public virtual ICollection<Course> CoursesTutored { get; set; }
    ...
}

我有以下映射:

modelBuilder.Entity<Course>().HasMany(x => x.Tutors)
                           .WithMany(p => p.CoursesTutored)
                           .Map(x =>
                               {
                                   x.MapLeftKey("PersonID");
                                   x.MapRightKey("CourseID");
                                   x.ToTable("Course_Tutors");
                               });

这样可以设置Course_Tutors表,并提供包含Leader_PersonIDCreatedBy_PersonIDUpdatedBy_PersonID的课程表。

但是,它还会在课程表中创建三个额外的Person列:Person_PersonID1Person_PersonID2Person_PersonID3

有人可以告诉我如何摆脱这些吗?我假设我的映射需要更多的工作。

1 个答案:

答案 0 :(得分:4)

当您在两个实体之间存在多个关系时,Code First在通过转化识别关系时遇到问题。您需要明确配置它们。

modelBuilder.Entity<Course>()
     .HasRequired(c => c.Leader)
     .WithMany(p => p.CoursesLead)
     .Map(m => m.MapKey("Leader_PersonID"));

modelBuilder.Entity<Course>()
     .HasRequired(c => c.CreatedBy)
     .WithMany(p => p.CoursesCreated)
     .Map(m => m.MapKey("CreatedBy_PersonID"));

modelBuilder.Entity<Course>()
     .HasRequired(c => c.UpdatedBy)
     .WithMany(p => p.CoursesUpdated)
     .Map(m => m.MapKey("UpdatedBy_PersonID"));