Visual Studio 2019 Preview
二、建立項目
1.建立一個MVC項目,和一個類庫
2..安裝NuGet包
(1)在ShopSystem.Model導入以下包
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Relational
Pomelo.EntityFrameworkCore.MySql
第一個坑:有的地方是推薦安裝MySql.Data.EntityFrameworkCore,但是我用後在生成資料庫時報錯了,一查好像是到現在為止他還沒有完成對.net core 3.1支援,是以我們安裝Pomelo.EntityFrameworkCore.MySql。
第二個坑:就是Microsoft.EntityFrameworkCore和Microsoft.EntityFrameworkCore.Relational不要安裝5.0及以上版本,不然後面也會報錯,因為pomelo還不支援.NET 5,不過我看了他在Github上的官方V5.0正式版不久也要到了。
(2)在ShopSystem導入以下包:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Tools
Microsoft.VisualStudio.Web.CodeGeneration.Design
3.在ShopSystem.Model下建立實體類和資料庫操作上下文
商品類Commodity:
using System;
namespace ShopSystem.Model
{
public class Commodity
{
public int Id { get; set; }
public string Name { get; set; }
public float Price { get; set; }
}
}
資料庫操作上下文:ShopContext:
using Microsoft.EntityFrameworkCore;
namespace ShopSystem.Model.Context
{
public class ShopDbContext: DbContext
{
public ShopDbContext(DbContextOptions options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
public DbSet Commodity { get; set; }
}
}
項目結構:
4.配置連接配接字元串
(1)在ShopSystem下的Appsetting配置連接配接字元串
"ConnectionStrings": {
"ShopDB": "Server=localhost;DataBase=ShopDB;uid=root;pwd=Tang380821;pooling=true;port=3306;CharSet=utf8;sslMode=None;"
}
第三個坑:注意:sslMode=None必須要加不然會到後面生成資料庫的時候會報錯。
5.在ShopSystem下Startup.cs中的ConfigureServices注入資料庫服務
(1)首先要添加model層的引用
(2)然後在ConfigureServices加入
services.AddDbContext(p => p.UseMySql(Configuration.GetConnectionString("ShopDB")));
5.開始遷移
依次點選 工具=》NuGet包管理器=》程式包管理器控制台,設定ShopSystem.Model為預設項目,ShopSystem為啟動項目。
(1)檢視遷移 Enable-Migrations
這裡顯示可以添加遷移
(2)添加遷移 Add-Migration "名字"
這個時候可以看到已經添加好了,同時多了一個遷移記錄的檔案夾
然後我們檢視一下資料庫,看到是沒有ShopDB的,因為這個時候還沒有把改動更新到資料庫
(3)更新資料庫 Update-Database
這個時候再回去看一下資料庫已經更新成功