11.Configure Many-to-Many(配置多对多关系)【Code-First系列】

时间:2023-03-09 13:21:39
11.Configure Many-to-Many(配置多对多关系)【Code-First系列】

现在学习EF Code-First多对多的配置。

这里我们举例:学生和班级实体,一个学生可以选修多个课程,多个学生也可以选修同一个课程。

一、使用数据注解特性,配置多对多的关系

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF7
{
   public class Student
    {
       public int StudentId { get; set; }

       public string StudentName { get; set; }

       public virtual ICollection<Course> Courses { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EF7
{
   public class Course
    {
       public int CourseID { get; set; }

       public string CourseName { get; set; }

       public ICollection<Student> Students { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF7
{
   public class DbContextClass:DbContext
    {
       public DbContextClass()
           : base("ConnectionStrings")
       {
           Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbContextClass>());
       }

       public DbSet<Student> Students { get; set; }

       public DbSet<Course> Courses { get; set; }
    }
}

然后生成的数据库:

11.Configure Many-to-Many(配置多对多关系)【Code-First系列】

11.Configure Many-to-Many(配置多对多关系)【Code-First系列】

11.Configure Many-to-Many(配置多对多关系)【Code-First系列】

上面的代码,是Code-First默认约定,帮我们自动配置的多对多关系。,可以看到生成了一个中间表StudentCourse。

二、现在让我们来使用Fluent API来配置多对多的关系吧:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF7
{
   public class DbContextClass:DbContext
    {
       public DbContextClass()
           : base("ConnectionStrings")
       {
           Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbContextClass>());
       }

       public DbSet<Student> Students { get; set; }

       public DbSet<Course> Courses { get; set; }

       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {
           modelBuilder.Entity<Student>().HasMany(s => s.Courses).WithMany(s => s.Students).Map(m =>
           {
               m.MapLeftKey("CourseRefID");
               m.MapRightKey("StudentRefID");
               m.ToTable("哇哈哈哈", "xxx");
           });
           base.OnModelCreating(modelBuilder);
       }
    }
}

11.Configure Many-to-Many(配置多对多关系)【Code-First系列】

11.Configure Many-to-Many(配置多对多关系)【Code-First系列】

11.Configure Many-to-Many(配置多对多关系)【Code-First系列】

好了这就是多对多的关系的配置了。

附上目录: