近期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.NET\ConsoleApp.NewDbByDp2\ConsoleApp.NewDbByDp2\Migrations\20170318Migration.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; } } }