asp.net Core EF core ( Entity Framework 7 ) 数据库更新维护

CreateData­baseIfNotExists等之前的API已经废弃,现在采用的是微软封装好,简化、高效的API,migrations

因为,旧API,要付出高昂的代价,以及局限性

打开VS2017,选择工具->NutGet包管理器->程序包管理器控制台

1.输入Add-Migration MyFirstMigration 指令

就会根据当前的dbcontext自动生成Migrations文件夹及文件,这些文件用于新建、或者扩展专属于Migrations 这个API的扩展的数据库

然后在asp.NET core的Startup.cs文件, public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 

Configure这个函数,加上

 2.update-database 升级数据库

[csharp] view plain copy
 
 print?在CODE上查看代码片派生到我的代码片
  1. using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())  
  2. {  
  3.     serviceScope.ServiceProvider.GetService<UnicornStoreContext>().Database.Migrate();  
  4.     serviceScope.ServiceProvider.GetService<ApplicationDbContext>().Database.Migrate();  
  5.     serviceScope.ServiceProvider.GetService<UnicornStoreContext>().EnsureSeedData();  
  6. }  


根据上面的代码换成自己的函数,即可

然后就可以根据生成的Mingrations文件夹内的文件,生成Mingrations API专属数据库,自动扩展,升级数据库

转载:http://blog.csdn.net/loongsking/article/details/63682952

原文地址:https://www.cnblogs.com/louby/p/6602273.html