1. 程式人生 > >.NetCore2.0下使用EF CodeFirst創建數據庫

.NetCore2.0下使用EF CodeFirst創建數據庫

img level framework 結構 time image startup spa override

本文所使用的VS版本:VS2017 15.3.0

首先新建一個.net core項目 取名NetCoreTask

技術分享

使用模型視圖控制器方式

技術分享

新建Model層

技術分享

在Model層下新建一個user實體類 

1 namespace XX.Model
2 {
3     public class tb_User
4     {
5         public string ID { get; set; }
6         public string UserName { get; set; }
7         public DateTime CreateTime { get
; set; } 8 } 9 }

新建一個Service層 在下面新建一個dbContext類  

 1 namespace XX.Service
 2 {
 3     public class XDbContext : DbContext
 4     {
 5         public XDbContext(DbContextOptions<XDbContext> options) : base(options)
 6         {
 7 
 8         }
 9         public DbSet<tb_User> UserExtend { get
; set; } 10 protected override void OnModelCreating(ModelBuilder modelBuilder) 11 { 12 base.OnModelCreating(modelBuilder); 13 } 14 } 15 }

在Web項目下的appsettings.json文件中添加數據庫連接字符串,添加後如下:  

 1 {
 2   "ConnectionStrings": {
 3     "XConnection": "Server=127.0.0.1;Database=XCoreDb;User ID=sa;Password=123456
" 4 }, 5 "Logging": { 6 "IncludeScopes": false, 7 "LogLevel": { 8 "Default": "Warning" 9 } 10 } 11 }

接下來修改 Web項目下的Startup中的ConfigureServices方法,修改後如下:

1 public void ConfigureServices(IServiceCollection services)
2         {
3             services.AddDbContext<XDbContext>(options =>
4                 options.UseSqlServer(Configuration.GetConnectionString("XConnection")));
5             services.AddMvc();
6         }

配置工作已經完成,接下來我們使用控制臺命令生成數據庫 FirstMigration這個名字是隨便起的(定位在Service項目下)

PM> Add-Migration FirstMigration

果不其然報錯了

技術分享

這是因為我們的Web項目和Service沒有什麽關系,添加Web項目對Service項目的引用後繼續

技術分享

成功了!

我們發現Service項目下多了一個文件夾

技術分享

但是我們發現在Designer.cs這個文件中有一個錯誤

技術分享

這是因為我們沒有添加 Microsoft.EntityFrameworkCore.SqlServer 這個引用

添加後,繼續執行Update-Database -Verbose 命令

1 PM>  Update-Database -Verbose

技術分享

出現這個就是成功了。

技術分享

數據庫創建成功!

最後的項目結構圖:

技術分享

.NetCore2.0下使用EF CodeFirst創建數據庫