zoukankan      html  css  js  c++  java
  • Entity Framework 多对多映射

    上一篇文章我们讲解了EF中的一对对多的关系映射,这篇文章我们讲解EF中的多对多(Many-to-Many Relationship)关系映射。这篇文章我们同样通过一个简单的例子来讲解多对多的关系映射。

    零、自动生成关系表

    故事:在一个学生选课系统中,存在学生和课程两个实体,他们之间的关系是:一个学生可以选择多门课程,一门课程也可以被多个学生选择。

    通过上面简单的描述,我们可以分析出学生和课程是多对多的关系。这种关系应设在数据库中就需要第三张表来辅助维持。这个第三张表被称为关联表或链接表,这张表中存存储了学生和课程的主键(或被能够区分唯一性的字段)。现在我们看一下,通过代码怎么来表示多对多关系:

    //学生类
    public class Student:BaseEntity
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public virtual ICollection<Course> Courses { get; set; }
    }
    //课程类
    public class Course : BaseEntity
    {
        public string Name { get; set; }
        public string TeacherName { get; set; }
        public virtual ICollection<Student> Students { get; set; }
    }
    //基础类
    public class BaseEntity
    {
        public int Id { get; set; }
        public DateTime CreateDateTime { get; set; }
    }
    

    同上一篇文章一样,我们创建 StudentCourse 的映射类

    //学生映射类
    public class StudentsMap : EntityTypeConfiguration<Student>
    {
        public StudentsMap()
        {
            //表名称
            ToTable("Students");
            //主键
            HasKey(p => p.Id);
    
            //设置主键自增长
            Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            //设置要映射的数据
            Property(p => p.Name).HasColumnType("VARCHAR").HasMaxLength(50);
            Property(p => p.Age);
            Property(p => p.CreateDateTime);
    
            //设置关系
            HasMany(p => p.Courses)
                .WithMany(p => p.Students)
                .Map(p => p.ToTable("StudentCourses")
                    .MapLeftKey("StudentId")
                    .MapRightKey("CourseId"));
    
        }
    }
    //课程映射类
    public class CourseMap : EntityTypeConfiguration<Course>
    {
        public CourseMap()
        {
            ToTable("Coureses");
            HasKey(p => p.Id);
            Property(p => p.Id)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(p => p.Name).HasColumnType("VARCHAR").HasMaxLength(50);
            Property(p => p.TeacherName);
            Property(p => p.CreateDateTime);
        }
    }
    

    从上面的 学生映射类 可以看出,一个学生可以选择多门课程,一个课程可以被多名学生选择。我们为了实现学生和课程多对多的关系,于是定义了关联表,并且设置了这个关联表中两个外键的名称。

    注:

    1. 在设置多对多关系的时候,如果不定义 MapLeftKeyMapRightKey EF将默认使用 实体类型_id 。在本例中如果不定义这两个键的名称的话,EF默认使用的名称是 Student_IdCourses_Id
    2. MapLeftKey 是关系键

    下面我们编写一段代码来测试一下数据库生成的是否是多对多的关系:

    static void Main(string[] args)
    {
        using (var efContext = new EFContext())
        {
            Student student = new Student
            {
                Name = "张三",
                Age = 26,
                CreateDateTime = DateTime.Now,
                Courses = new List<Course>
                {
                    new Course
                    {
                        Name="语文",
                        TeacherName="王老师",
                        CreateDateTime=DateTime.Now
                    },
                    new Course
                    {
                        Name="数学",
                        TeacherName="孙老师",
                        CreateDateTime=DateTime.Now
                    }
                }
            };
    
            Course course = new Course
            {
                Name = "英语",
                TeacherName = "Jack",
                CreateDateTime = DateTime.Now,
                Students = new List<Student>
                {
                    new Student
                    {
                        Name="王五",
                        Age=27,
                        CreateDateTime=DateTime.Now
                    },
                    new Student
                    {
                        Name="孙琦",
                        Age=27,
                        CreateDateTime=DateTime.Now
                    }
                }
            };
    
            efContext.Students.Add(student);
            efContext.Courses.Add(course);
            efContext.SaveChanges();
        }
    }
    

    代码运行后,数据库将出现三张表 StudentsCouresesStudentCourses ,其中 StudentCourses关联表 ,该表中将出现 StudentsCoureses 之间的关系

    ZITyM6.png

  • 相关阅读:
    python装饰器的作用
    python的__call__、__str__、__repr__、__init__、__class__、__name___、__all__、__doc__、__del__等魔术方法的作用
    安全小测试:介绍一个简单web安全知识测试的网站
    浏览器都知道我们的哪些信息?
    SQL开发技巧(二)
    如何解决SQLServer占CPU100%
    记一次SQLServer的分页优化兼谈谈使用Row_Number()分页存在的问题
    如何在SQLServer中处理每天四亿三千万记录
    SqlServer索引的原理与应用
    T-sql语句查询执行顺序
  • 原文地址:https://www.cnblogs.com/gangzhucoll/p/12778196.html
Copyright © 2011-2022 走看看