您的位置:首页 > 编程语言 > ASP

.net core 1.1下的EntityFramework Code First

2017-01-27 08:58 579 查看
新建asp.net core项目,然后把.net core引用的类库升级到1.1,这时,需要手动在project.json下添加一个runtimes节点,如下:
"runtimes": { "win10-x64": {}} 同时在Nuget中添加下面三个类库(1.1版本):
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools

接下来定义DbContext,用来生成数据库,代码如下:
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace EntityFrameworkDemo.Model
{
/// <summary>
/// 数据库对象
/// </summary>
public class PermissionContext : DbContext
{
public PermissionContext(DbContextOptions<PermissionContext> opt) : base(opt)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//确定UserRole表中的两个字段是联合主键
modelBuilder.Entity<UserRole>()
.HasKey(u=>new { u.UserID,u.RoleID});
}
public DbSet<User> Users
{ get; set; }
public DbSet<Role> Roles
{ get; set; }

public DbSet<UserRole> UserRoles
{ get; set; }
}
/// <summary>
/// 用户表
/// </summary>
public class User
{
[Key]
public int ID
{ get; set; }
public string UserName
{ get; set; }

public string Password
{ get; set; }

public List<UserRole> UserRoles { get; set; }
}
/// <summary>
/// 角色表
/// </summary>
public class Role
{
[Key]
public int ID
{ get; set; }
public string RoleName
{
get;set;
}
public List<UserRole> UserRoles { get; set; }
}
/// <summary>
/// 用户角色关系
/// </summary>
public class UserRole
{

public int UserID
{ get; set; }

public int RoleID
{ get; set; }

public User User{ get; set; }
public Role Role { get; set; }
}
}

这时,需要在StartUp.cs中添加数据连字符串,来指导自动生成数据库时的服务器,数据库名等信息
public void ConfigureServices(IServiceCollection services)
{
var connection = @"Server=.;Database=PermissionDb;Trusted_Connection=True;";
services.AddDbContext<PermissionContext>(options => options.UseSqlServer(connection));

services.AddMvc();
}

现在,先Build一下项目,用两个命令在程序包管理器控制台(vs的菜单“工具”-“NuGet包管理器”-“程序包管理器控制台”)中执行:
Add-Migration MyFirstMigration
用来生成命令,生成数据库和表的C#代码
Update-Database
执行生成的代码
在用Add-Migration MyFirstMigration时会报个错,在netcoreapp1.1中没有需要的项目配置文件(.json的),这时打开bin目录,会发现在netcoreapp1.1下会多一个win10-x64文件夹,这正是我们手工在project.json中添加的,打开这个文件夹,把里面对应的.json复制出来就可以(这里应该是Add-MigrationMyFirstMigration生成代码时,默认的寻找配置文件与我们手工添加runtimes的路径不一直导致)



复制完后再Add-Migration MyFirstMigration一次
会发现在项目中添加了一个文件夹Migrations,并在下面生成两个文件,这便是生成数据库所需的指令。
现在再执行Update-Database



当执行成功后,用SQL Server的管理工具查看,生成的数据库,并且表中的表关系入下:


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  asp ef entityframework