天天看点

codefirst连接mysql_EFCore CodeFirst 连接MySql

一.工具及环境

Visual Studio 2017 15.4.3

MySql

Navicat for MySQL

二.Entity Framwork Core 2.0 MySql Code First 及 数据库迁移(Migrations)

1.创建Asp.Ner Core 应用程序

2.项目创建完成之后通过程序包管理器控制台,引入下面两个包

搜索 Microsoft.EntityFrameworkCore.Tools及 Pomelo.EntityFrameworkCore.MySql 然后安装就可以了

3.编辑 项目文件,增加这段。通过NuGet安装不来

codefirst连接mysql_EFCore CodeFirst 连接MySql

4.创建User类

public class User

{

public int Id { get; set; }

public string Name { get; set; }

public string Age { get; set; }

}

5.添加DataContext类

codefirst连接mysql_EFCore CodeFirst 连接MySql

public class DataContext : DbContext

{

public DataContext(DbContextOptions options)

: base(options)

{

}

public DbSet Users { get; set; }

}

codefirst连接mysql_EFCore CodeFirst 连接MySql

6.打开Startup.cs 在ConfigurationServices方法中添加连接MySql的相关代码

codefirst连接mysql_EFCore CodeFirst 连接MySql

public void ConfigureServices(IServiceCollection services)

{

services.AddMvc();

//这里就是填写数据库的连接字符串

var connection = "Server=localhost;Port=3306;Database=TestMySql; User=root;Password=;";

services.AddDbContextPool(options => options.UseMySql(connection));

}

codefirst连接mysql_EFCore CodeFirst 连接MySql

7.在项目根目录,按Shift+鼠标右键,选择打开PowerShell(如果是打开cmd也是可以的)

8.输入 dotnet ef Migrations add Init

9.执行成功之后,输入 dotnet ef database update

执行成功后,可以看到数据库创建成功

codefirst连接mysql_EFCore CodeFirst 连接MySql

10.修改实体,并把修改的实体更新到数据库(其实就是增加一些列)

这里增加了Email列,但是这时数据库还没有Email列,接下来我们通过命令更新到数据库中

codefirst连接mysql_EFCore CodeFirst 连接MySql

上图命令其实跟刚开始 dotnet ef Migrations add Init 性质是一样的,只要你更改了代码中的实体,然后想要更新到数据库中

就是执行 dotnet ef add Migrations add 自定义名称(注意是英文名称)

然后执行 dotnet ef database update 执行成功之后,可以看到数据库中也添加了刚才我们增加User实体中的Email列

codefirst连接mysql_EFCore CodeFirst 连接MySql

另一种方法是在VS菜单》视图》其它窗口》程序包管理器控制台:

enable-migrations

add-migration init

update-database