我有Person
和Course
实体有多种关系:
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_PersonID
,CreatedBy_PersonID
和UpdatedBy_PersonID
的课程表。
但是,它还会在课程表中创建三个额外的Person
列:Person_PersonID1
,Person_PersonID2
,Person_PersonID3
。
有人可以告诉我如何摆脱这些吗?我假设我的映射需要更多的工作。
答案 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"));