.net core code frist帶資料庫遷移
阿新 • • 發佈:2018-11-10
1、新建.net core 工程。
2、新增類book。
public class Book { public int ID { get; set; } public string Name { get; set; } public DateTime ReleaseDate { get; set; } public string Author { get; set; } public decimal Price { get; set; } }
3、新增資料庫上下文類
public class BookContext : DbContext { public BookContext(DbContextOptions<BookContext> options) : base(options) { } public DbSet<Book> Book { get; set; } }
4、新增配置檔案資料庫連線字串
5、註冊資料庫上下文
在Visual Studio 2017中的資源管理器中找到startup.cs檔案,用滑鼠雙擊開啟,在startup.cs檔案的ConfigureServices方法中寫入依賴注入容器註冊資料庫上下文的程式碼,具體程式碼如下。
發現UseMySql標紅色,是由於專案沒有引用Pomelo.EntityFrameworkCore.MySql。新增引用。
6、新增 Microsoft.EntityFrameworkCore.Tools
7、執行初始遷移
• 執行Add-Migration Initial生成程式碼檔案。
• 執行Update-Database命名,生成或更新資料庫。
發現數據庫已經生成成功