简体   繁体   English

在代码优先C#中出现多对多关系

[英]Issue with many to many relationship in code first c#

I am using entity framework code first for creating database in my project. 我首先使用实体​​框架代码在我的项目中创建数据库。 I have defined many to many relationship between following two table.: 我定义以下两个表之间的多对多关系:

  1. Student 学生
  2. Course 课程

Fluent Api 流利的Api

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

This will define a many to many relationship between Student and Course and will create a new table StudentCourse in the database. 这将定义学生课程之间的多对多关系,并将在数据库中创建一个新表StudentCourse

Now i want to define a new relationship (that may be 1 to 1 OR 1 to many ) between 现在我想定义一个新的关系(可能是1对11对许多

  1. StudentCource 学生课程
  2. Any other table 任何其他表

How can i do this with entity framework code first ?? 我该如何首先使用实体​​框架代码做到这一点?

What do you want is no possible without creating a own class (poco) for the StudentCourse 如果没有为StudentCourse创建自己的课程(poco),那么您想要的是不可能的

public class StudentCourse
{
    public int Id {get;set;}
    public Student Student {get; set;}
    public Course Course {get; set;}

}

And then use fluent api to make the relationship between this three variables 然后使用流畅的api来建立这三个变量之间的关系

modelBuilder.Entity<StudentCourse>()
    .HasRequired(i => i.Student)
    .WithMany(u => u.StudentCourses)
    .HasForeignKey(i => i.StudentId)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<StudentCourse>()
    .HasRequired(i =>i.Course)
    .WithMany(d =>d.StudentCourses)
    .HasForeignKey(i => i.CourseId)
    .WillCascadeOnDelete(false);

Where StudentCourses are the navigation properties in the student class and Course class 其中StudentCourses是学生班和课程班的导航属性

You can use the Id defined as primary key or use the foreign key of both tables as primary: 您可以使用定义为主键的ID或将两个表的外键都用作主键:

modelBuilder.Entity<StudentCourse>()
    .HasKey(i => new {i.StudentId,i.CourseId });

In my opinion use the Id as primary key make you more simple the things for making relationships between StudentCourse and another table. 在我看来,使用ID作为主键可以使在StudentCourse与另一个表之间建立关系的事情变得更加简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM