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; }
    }
}

然后生成的数据库:

 

上面的代码,是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);
       }
    }
}

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

 

附上目录:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值