配置实体之间的多个关系

本文关键字:关系 实体 之间 配置 | 更新日期: 2023-09-27 18:19:56

我有具有多个关系的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

有人能告诉我如何去掉这些吗?我想我的地图需要更多的工作。

配置实体之间的多个关系

当两个实体之间有多个关系时,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"));