最近一直在捣鼓.NET Core方面的东西,顺便写下点东西记录下
1、打开vs2017,新建一个项目
2、vs会自动生成一个项目,然后打开NuGet搜索MySql.Data.EntityFrameworkCore下载
3、然后在Models下面新建一个Student类,然后再新建一个类继承DbContext类
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks; namespace MySql.Test.Models
{
public class Student
{
[Key]
public int ID { get; set; }
[Display(Name="姓名")]
public string Name { get; set; }
[Display(Name="年龄")]
public int Age { get; set; }
}
}
public class MysqlDbContext : DbContext
{
public MysqlDbContext(DbContextOptions<MysqlDbContext> options):base(options)
{ }
//protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
//{
// optionsBuilder.UseMySQL("server=.;database=TestDb;user=root;password=123456;");
//}
//protected override void OnModelCreating(ModelBuilder modelBuilder)
//{
// base.OnModelCreating(modelBuilder);
//} public DbSet<Student> students { get; set; }
}
这里说明下MySQL连接也可以写在这里,但我们后面会注入到services中
4、然后我们在appsettings.json里添加一个连接字符串(.NET Core使用在appsettings.json里读取配置,类似于webconfig)
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": { "MysqlConnection": "Data Source=.;Database=TestDb;User ID=root;Password=123456;pooling=true;port=3306;sslmode=none;CharSet=utf8;" }
}
5、然后打开Startup,将MySQL连接注入services,具体Startup使用可以去看相关博客
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
}); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); var connection = Configuration.GetConnectionString("MysqlConnection");
services.AddDbContext<MysqlDbContext>(options => options.UseMySQL(connection));
}
6、然后我们就可以开始数据迁移了
在vs中的“程序包管理器控制台”中输入如下两个命令
Add-Migration init(执行此命令项目生成一个目录(Migration))
Update-Database init
然后我们就可以在数据库看到生成的数据库以及数据表了
注意:如果出现错误提示xxxx.__EFMigrationsHistory doesn't exist
我们需要手动在数据库创建__EFMigrationsHistory这张表
然后再开始迁移就好了
最后还遇到一个问题是:如果已经数据迁移后,又在Models添加一个类再次更新时需要指定到具体的表名,不然会提示原来的表已经存在,或者删除原来的数据表(不推荐)。