Cấu hình quan hệ nhiều nhiều trong Entity Framework Core

Không có quy định nào có sẵn trong việc xây dựng quan hệ nhiều nhiều trong EF Core.



Bạn cần làm như thế này:

public class StudentCourse
{
    public int StudentId { get; set; }
    public Student Student { get; set; }
    public int CourseId { get; set; }
    public Course Course { get; set; }
}

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }
    public IList<StudentCourse> StudentCourses { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public string Description { get; set; }
    public IList<StudentCourse> StudentCourses { get; set; }
}

Bảng StudentCourse cần thiết trong ef core, nó không còn tự sinh ra!

Tip: Nếu bạn sử dụng Identity có thể bạn sẽ cần thêm đoạn này trong file DbContext:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<PostCategory>().HasKey(pc => new { pc.PostId, pc.CategoryId });
            modelBuilder.Entity<PostTag>().HasKey(pt => new { pt.PostId, pt.TagId });
            base.OnModelCreating(modelBuilder);
        }
Tham khảo:
http://www.entityframeworktutorial.net/efcore/configure-one-to-one-relationship-using-fluent-api-in-ef-core.aspx
Post a Comment