zoukankan      html  css  js  c++  java
  • EntityFramework Code-First 简易教程(十)-------多对多

    配置Many-to-Many(多对多)关系:

    这里有两个类,Student和Course,一个Student可以有多个Course,一个Course也可以有多个Student,所以这就成了多对多关系。更多信息请访问Entity Relationship

    进入正题:

    1.使用DataAnnotation配置多对多关系:

    Student类中有一个Course的集合属性,在Course类中也有一个Student的集合属性,这样就默认配置成了多对多关系。代码如下:

    public class Student
    {
        public Student() { }
    
        public int StudentId { get; set; }
        [Required]
        public string StudentName { get; set; }
    
        public int StdandardId { get; set; }
            
        public virtual ICollection<Course> Courses { get; set; }
    }
            
    public class Course
    {
        public Course()
        {
            this.Students = new HashSet<Student>();
        }
    
        public int CourseId { get; set; }
        public string CourseName { get; set; }
    
        public virtual ICollection<Student> Students { get; set; }
    }

    上面的代码将会创建如下的数据库,这里会新建一张表CourseStudents,这张新表里面记录着对多对关系的两个表的外键StudentId和CourseId(当然在CourseStudents表中这两列即是主键又是外键)。

    one-to-one relationship in code first

    2.使用Fluent API配置多对多关系:

    直接上配置代码:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    
        modelBuilder.Entity<Student>()
                    .HasMany<Course>(s => s.Courses)
                    .WithMany(c => c.Students)
                    .Map(cs =>
                            {
                                cs.MapLeftKey("StudentRefId");
                                cs.MapRightKey("CourseRefId");
                                cs.ToTable("StudentCourse");
                            });
    
    }

    如你所见,上面的例子中, .HasMany<Course>(s => s.Courses).WithMany(c => c.Students) 告诉Student和Course有多对多关系。

    Map方法可以传入一个委托,所以这里可以使用lambda表达式,其中,MapLeftKey方法指定了Student的外键属性名称(这里先指定Student,所以它是左表)和Course表的外键,ToTable方法将创建StudentCourse表。

    这样数据库将会创建一个新表StudentCourse,CourseRefId和StudentRefId既是主键又是外键。

    one-to-one relationship in code first

    到此,一对一,一对多,多对多的关系我们就讲完了,基本上能应对大多数情况的开发了。

  • 相关阅读:
    lamp环境的搭建
    http与HTTPS的区别
    共有多少协议
    海纳百川下载器(道客巴巴免费下载器)程序已停止工作解决方法
    海纳百川下载器使用方法图文详解
    怎么用几何画板打出角度符号?
    几何画板怎样画半圆
    如何使用Adobe Reader复制PDF文档上的文字
    ADOBE READER把PDF转换成WORD教程
    photoshopcs6破解补丁用来干嘛的
  • 原文地址:https://www.cnblogs.com/tang-tang/p/5636973.html
Copyright © 2011-2022 走看看