VS2019+MVC+EF6-CodeFirst 鏈接MySQL
一、準備環境(經過NuGet獲取)
EntityFramework
![](http://static.javashuo.com/static/loading.gif)
MySql.Data.Entity
![](http://static.javashuo.com/static/loading.gif)
安裝後確認
![](http://static.javashuo.com/static/loading.gif)
二、在MVC-Model文件夾下添加一個學生類,後面用它經過[數據遷移]在MySQL中建立一個表
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
}
三、建立數據上下文 (先引入 using System.Data.Entity;
)
namespace EFToMysqlDemo
{
// [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))] 若是去掉這一句,EF自動建立數據庫時會報錯,而此時建立控制器又會報錯,因此建立控制器的時候註銷這句就能夠了
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class EFDemoContext:DbContext
{
static EFDemoContext()
{
//開發環境中,若是數據結構發生變化,須要從新建庫,每次建庫後要從新插入測試數據,能夠用DropCreateDatabaseIfModelChanges類來實現(生成環境中請使用 Migrations作數據遷移)
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EFDemoContext>());
}
public EFDemoContext():base("EFToMysqlCon") { }
public DbSet<Student> Students { get; set; }
}
}
四、配置文件中添加連接字符串
4.1 具體參數按本身的作相應修改
<connectionStrings>
<add name="EFToMysqlCon" connectionString="Data Source=127.0.0.1;port=3306;Initial Catalog=EFDemoDb;user id=root;password=123456;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
五、數據遷移
5.1 數據遷移經常使用命令
命令1:啓動EF數據遷移
Enable-Migrations -ContextTypeName 命名空間.上下文名稱
命令2:建立遷移文件
Add-Migration 自定義名稱
命令3:更新數據庫
Update-Database
5.2 打開程序包管理器控制檯
![](http://static.javashuo.com/static/loading.gif)
5.3 按經常使用命令(5.1)依次執行
![](http://static.javashuo.com/static/loading.gif)
5.4 經過Navicat查看MySQL
![](http://static.javashuo.com/static/loading.gif)