簡體   English   中英

與查找表實體框架的多對多關系

[英]Many to Many Relation with Lookup table Entity Framework

我正在嘗試使用查找表創建多對多關系。 假設我有一個表“ Course”,其中有3個可能的課程:

Course
Id | Name
1  | History
2  | Maths
3  | Science

我還有另一個學生表,將在其中創建學生,例如:

Student
Id | Name

我有一個映射表,它是StudentCourse:

StudentCourse
ID | StudentId | CourseId
1  |   1       | 3

這是我的學生與課程課程:

public class Student : Entity<Student,int>
{
    public virtual ICollection<Course> Courses { get; set; }
}

public class Course : Entity<Course,int>
{
    public virtual ICollection<Student> Student { get; set; }
}

最后,這是配置代碼:

   modelBuilder.Entity<Student>()
                .HasMany<Course>(s => s.Courses)
                .WithMany(c => c.Students)
                .Map(cs =>
                        {
                            cs.MapLeftKey("StudentId");
                            cs.MapRightKey("CourseId");
                            cs.ToTable("StudentCourse");
                        });

當我從視圖創建“學生”實體時,用戶從“課程”表中選擇課程並將其發送到實體框架,EF應該僅輸入“學生”和“學生課程”表。

但是在我的情況下,課程表正在為所選課程獲取新條目。 因此,我最終在課程表中找到了重復項。

我該如何告訴實體框架不要在“課程表”中輸入條目,因為它已經具有所有可能的課程……請幫助!

問題是我在表示層中填充了對象,因此工作單元下的dbcontext不了解嵌套的對象。這就是為什么即使它已經存在,它也總是嘗試重新創建課程的原因。 要解決此問題,請在同一工作單元dbcontext下填充Course對象。

例如:

  student.Course = UnitOfWork.Repository.FindById(id);
  var model = UnitOfWork.Repository.Add(student);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM