ASP.NET EntityFrameworkCore code first 多对多设计

参考网址:https://docs.microsoft.com/zh-cn/ef/core/get-started/full-dotnet/new-db

场景:使用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创建项目;

2.NuGet添加 Microsoft.EntityFrameworkCore.SqlServer

3.创建如下三个类

 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 BranchOffice BranchOffice { get; set; }

        public List<UserRole> UserRoles { get; set; }


    }
AppUser 类
 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类
 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.创建DBContext

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

            modelBuilder.Entity<UserRole>()
                        .HasOne(userrole => userrole.AppUser)
                        .WithMany(user => user.UserRoles)
                        .HasForeignKey(userrole => userrole.AppUserID);

            modelBuilder.Entity<UserRole>()
                        .HasOne(userrole => userrole.AppRole)
                        .WithMany(role => role.UserRoles)
                        .HasForeignKey(userrole=> userrole.AppRoleID);
        }


        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=sandbox.XXXX.com;Initial Catalog=API;Persist Security Info=True;User ID=sa;Password=XXXXX;");
        }
    }
DbContext类

5.运行 Add-Migration APIMigration 

运行结束后,可以发现项目中多了 APIMigration.cs

6.运行Update-Database,生成数据库。

检查数据库生成结果:

 

检查UserRoles表的外键:

至此,创建多对多的实体成功。

 

posted @ 2017-03-16 21:59  shuzhen.yu  阅读(557)  评论(1编辑  收藏  举报