MySql EF Core CodeFirst配置

最近想在linux上运行asp.net的网站项目,数据库用的mysql,想通过EF来连接MySQl,结果EFCore的资料极少,踩了无数坑解决问题,把过程整理下。

1.建立ASP.NET Core项目
添加Nuget程序包
Microsoft.EntityFrameworkCore
MySql.Data.EntityFrameworkCore(搜索时需要勾选包括预发行版)

2.建实体类
注意主键须添加[Key](位于System.ComponentModel.DataAnnotations命名空间)

3.建DbContext
按照如下格式

public class XXXContext : DbContext
{
public XXXContext(DbContextOptions options) : base(options)
{
}
public DbSet XXInfo
{
get;
set;
}
public DbSet XXXInfo
{
get;
set;
}
}

4.配置启动项
在Startup类中ConfigureServices方法
public void ConfigureServices(IServiceCollection services)
添加

services.AddDbContext(options => options.UseMySQL("server=你的服务器;userid=用户名;pwd=密码;port=端口;database=数据库名;sslmode=none;"));

或者也可以从配置文件读取数据库连接语句
在appsettings.json添加

"ConnectionStrings": {
"DefaultConnection": "server=你的服务器;userid=用户名;pwd=密码;port=端口;database=数据库名;sslmode=none;"
},

方法中的数据库连接语句位置改成Configuration.GetConnectionString("DefaultConnection")

5.打开NuGet程序包控制台
位于工具-Nuget包管理器-程序包管理控制台

6.安装工具包
在Nuget程序包控制台输入Install-Package Microsoft.EntityFrameworkCore.Tools

7.创建Migration
在Nuget程序包控制台输入Add-Migration xxx
xxx换成Migration的名字

8.更新数据库
在Nuget程序包控制台输入Update-Database

9.如果需要对数据库进行更改,只需对代码进行相应更改并重复78步骤即可

 

 

PS:踩了个巨坑,一直报这个错误
Could not load file or assembly ‘System.Diagnostics.DiagnosticSource, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51’. The located assembly’s manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

最后Github找到解决方案,顺便鄙视下百度,百度半天啥都没有,谷歌一下直接解决。
在csproj中加入如下



true

Posted in C#

发表回复

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据