简体   繁体   English

始终在EntityFramework Core中放置DropCreateDatabase

[英]DropCreateDatabaseAlways in EntityFramework Core

I need to make a website for school using ASP.Net CORE along with MVC in Visual Studio. 我需要使用ASP.Net CORE和Visual Studio中的MVC为学校创建一个网站。 There is also a database connected to this website, which uses Entity Framework CORE. 还有一个连接到该网站的数据库,该数据库使用Entity Framework CORE。 I have scaffolded quite a few models and the DbContext comes with it. 我已经搭建了很多模型,并且DbContext随之提供。 The actual problem: I want the program to Drop the database and Create a new one using Entity Framework CORE every time the program is run. 实际的问题:每次程序运行时,我都希望程序删除数据库并使用Entity Framework CORE创建一个新数据库。

I have found a lot articles about this same problem, but the solutions provided by them and the answers on other question by users on StackOverflow are not 'up to date' to the latest version of Entity Framework. 我已经找到了很多关于同一问题的文章,但是它们提供的解决方案以及用户在StackOverflow上对其他问题的回答都不是最新的Entity Framework。 In the older version, there was a neat solution to achieve my desired goal: simply use DropCreateDatabaseAlways and seed to immediately add data to the database. 在较旧的版本中,有一个巧妙的解决方案可以实现我期望的目标:只需使用DropCreateDatabaseAlways和seed即可立即将数据添加到数据库。 This option is gone in the new Core version (it isn't supported (yet)). 新的Core版本中没有此选项(尚不支持)。

After searching for a long and painfull time, I couldn't find anything that works with this version of Entity Framework. 经过漫长而痛苦的搜索,我找不到适用于此版本的Entity Framework的任何内容。

So I decided to ask you guys...! 所以我决定问你们...! The scaffolded DbContext starts like this. 脚手架的DbContext这样开始。 I don't think more code of this class is actually needed, since that's al modelBuilder calls and DbSets being instantiated. 我认为实际上并不需要更多此类的代码,因为这是modelBuilder调用和实例化的DbSets。 But tell me if you need more. 但是告诉我您是否还需要更多。

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

Any help would be very appreciated. 任何帮助将不胜感激。

Sorry for bad English. 对不起,英语不好。

Yes as you said DropCreateDatabaseAlways is EF 6. In EF Core I think you need to do the following: 是的,正如您所说的DropCreateDatabaseAlways是EF6。在EF Core中,我认为您需要执行以下操作:

context.Database.EnsureDeleted();
context.Database.EnsureCreated();
context.Database.Migrate();

See more here: How and where to call Database.EnsureCreated and Database.Migrate? 在此处查看更多信息: 如何以及在何处调用Database.EnsureCreated和Database.Migrate?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM