zoukankan      html  css  js  c++  java
  • EFCore+MSSS CodeFirst多对多设计初体验

    近期VS2017发布,EFCore更新到1.1,看了网上一篇博客:ASP.NET EntityFrameworkCore code first 多对多设计

     便想自己体验一番。

    场景:使用ASP.NET EntityFrameworkCore CODE FIRST 创建多对多实体

    需求:CODE FIRST实现多对多的实体创建。

    细节:

    创建两个实体类,一个是AppUser,一个是AppRole,两个实体通过UserRole关联。即一个AppUser可能隶属于多个AppRole,一个AppRole可能关联了多个AppUser。

    在EntityFrameworkCore 中,不支持两个实体之间的直接多对多,可以通过引入第三个实体,分别进行两次一对多来间接实现多对多。

    官方描述为:

    Many-to-many relationships without an entity class to represent the join table are not yet supported. However, you can represent a many-to-many relationship by including an entity class for the join table and mapping two separate one-to-many relationships.

    具体实现步骤如下:

    1.VS2017创建项目,这里贴出具体的步骤,更直观明了(注意截图中的文字)。

    注意:如果项目存储路径含有中文,报错如下:由于找不到源文件“D:������ĿѧϰASP.NETConsoleApp.NewDbByDp2ConsoleApp.NewDbByDp2Migrations20170318Migration.cs”,因此无法添加链接

    2.使用程序包控制台安装程序包

    在控制台PM后依次输入如下两行语句,添加程序号。

    Install-Package Microsoft.EntityFrameworkCore.SqlServer
    
    Install-Package Microsoft.EntityFrameworkCore.Tools
    

    3.在项目Models文件夹下创建三个类:AppUser、AppRole、UserRole(UserRole连接AppUser和AppRole实体,实现多对多)

    代码如下:  

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace ManyToMany.Models
    {
        public class AppUser
        {
    
            public int AppUserID { get; set; }
            public string Guid { get; set; }
    
            public string UserName { get; set; }
            public string LoginName { get; set; }
            public string LoginPassword { get; set; }
            public string Phone { get; set; }
            public string Email { get; set; }
            public int Sex { get; set; }
    
    
            public int BranchOfficeID { get; set; }
    
            public List<UserRole> UserRoles { get; set; }
    
        }
    }
    AppUser类
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace ManyToMany.Models
    {
        public class AppRole
        {
            public int AppRoleID { get; set; }
            public string Guid { get; set; }
            public string RoleName { get; set; }
    
            public List<UserRole> UserRoles { get; set; }
        }
    }
    AppRole类
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace ManyToMany.Models
    {
        public class UserRole
        {
            public int UserRoleID { get; set; }
    
    
            public int AppRoleID { get; set; }
            public AppRole AppRole { get; set; }
    
    
            public int AppUserID { get; set; }
            public AppUser AppUser { get; set; }
        }
    }
    UserRole类

    4.创建数据上下文类:ApiContext

    在Models文件夹下创建ApiContext类,添加引用using Microsoft.EntityFrameworkCore,完整类代码如下:

    using Microsoft.EntityFrameworkCore;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace ManyToMany.Models
    {
        public class ApiContext : DbContext
        {
    
            public DbSet<AppUser> AppUsers { get; set; }
    
            public DbSet<AppRole> AppRoles { get; set; }
    
            public DbSet<UserRole> UserRoles { get; set; }
    
    
            /// <summary>
            /// 通过第三张表UserRole 实现 多对多绑定 AppRole 和 AppUser
            /// </summary>
            /// <param name="modelBuilder"></param>
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<UserRole>()
                    .HasKey(t => new { t.AppRoleID, t.AppUserID });
    
                //实现一个AppUser对多个AppRole
                modelBuilder.Entity<UserRole>()
                            .HasOne(userrole => userrole.AppUser)
                            .WithMany(user => user.UserRoles)
                            .HasForeignKey(userrole => userrole.AppUserID);
    
                //实现一个AppRole对多个AppUser
                modelBuilder.Entity<UserRole>()
                            .HasOne(userrole => userrole.AppRole)
                            .WithMany(role => role.UserRoles)
                            .HasForeignKey(userrole => userrole.AppRoleID);
            }
    
            //配置SqlServer数据库
            //程序包管理器控制台输入 Add-Migration ApiMigration会在生成相应的数据库
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlServer(@"Server=DP_PCDPSQL2008;Initial Catalog=ApiDb;Persist Security Info=True;User ID=sa;Password=xx;");
            }
        }
    }
    ApiContext类

    5.在程序包管理器控制台中输入如下语句:

    Add-Migration ApiMigration

    该条语句执行完成后,会在项目中生成一个Migration文件夹,文件夹下包含两个cs文件,如下所示。

    6.接着在程序包管理器控制台中输入更新数据库语句,如下:

    Update-Database

    这时候,控制台会出现相应的数据库执行语句

    执行完成后查看数据库,可以发现已经生成了ApiDb数据库。

    查看UserRole表的外键关系。

    至此,使用EFCore CodeFirst已经实现了实体类的多对多映射关系。

  • 相关阅读:
    Vue 路由组件传参的 8 种方式
    JS中通过url动态获取图片大小的方法小结(两种方法)
    基于 Vue.js 实现的精致移动端组件库
    .net core 通过代码创建数据库表
    .net core 框架调用顺序
    POCO的理解
    winform datagridview 同步滚动
    UseIIS
    winform 多个datagridview 之间同步滚动
    winform BackgroundWorker 的用法
  • 原文地址:https://www.cnblogs.com/Med1tator/p/6573066.html
Copyright © 2011-2022 走看看