天天看點

EF架構的Code First實作

通過代碼生成資料庫

首先建一個.NET的類庫項目

EF架構的Code First實作

 然後裝一下EntityFramework

EF架構的Code First實作

 裝好之後會有App.config,在App.config中配置好連接配接資料庫的字元串

EF架構的Code First實作

 然後建立資料庫實體類,我這裡建了一個BaseEntity,其他的類繼承他。繼承的表都有ID和CreateTime

EF架構的Code First實作

 建立一個資料庫上下文類

EF架構的Code First實作

 打開程式包管理控制台,輸入enable-migrations,會在Migrations檔案夾下生成一個Configuration.cs

EF架構的Code First實作

 輸入add-migration 'createDb',會生成..._createDb.cs檔案

EF架構的Code First實作

 輸入update-database,就會生成資料庫了

EF架構的Code First實作
EF架構的Code First實作

更新資料庫

 更新資料庫,在User表中新增一個字段,然後更新會提示無法更新。将AutomaticMigrationsEnabled設為true,就好了

EF架構的Code First實作

 設為true之後更新

EF架構的Code First實作
EF架構的Code First實作

 删除字段,提示不能删除,加上AutomaticMigrationDataLossAllowed = true。

EF架構的Code First實作

 加上之後就能删除了

EF架構的Code First實作