最近一直在搗鼓.NET Core方面的東西,順便寫下點東西記錄下 1、打開vs2017,新建一個項目 2、vs會自動生成一個項目,然後打開NuGet搜索MySql.Data.EntityFrameworkCore下載 3、然後在Models下麵新建一個Student類,然後再新建一個類繼承DbCon ...
最近一直在搗鼓.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
我們需要手動創建
CREATE TABLE `__EFMigrationsHistory` ( `MigrationId` nvarchar(150) NOT NULL, `ProductVersion` nvarchar(32) NOT NULL, PRIMARY KEY (`MigrationId`) );
然後再開始遷移就好了
最後還遇到一個問題是:如果已經數據遷移後,又在Models添加一個類再次更新時需要指定到具體的表名,不然好像會出錯。