如果EF Core中的模型更改而没有迁移,则删除数据库 [英] Drop database if model changes in EF Core without migrations

查看:95
本文介绍了如果EF Core中的模型更改而没有迁移,则删除数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在先前版本的实体框架中,如果模型更改,则可以使用某些类DropDatabseIfModelChanges和其他相关类来重新创建数据库.在EF7或EF Core中,我不知道该怎么做.运行迁移有时会带来问题,在项目开始时,我需要不断更改模型.

In previous version of entity framework, one could recreate the database if the model changes, using some of the classes DropDatabseIfModelChanges and other related classes. In EF7 or EF Core i don't know how to do that. Run the migrations some times give problems and in the beginning of the project i need to change the models constantly.

推荐答案

目前尚没有在EFCore中实现 DropDatabseIfModelChanges 的简便方法.EF6的工作原理是将模型的快照存储在 __ MigrationHistory 表中,并将其与当前模型进行比较.EFCore中的 EnsureCreated 不会存储此类信息.

There's currently no easy way to implement DropDatabseIfModelChanges in EFCore. EF6 worked by storing a snapshot of your model in the __MigrationHistory table and comparing it to the current model. No such information is stored by EnsureCreated in EFCore.

要模仿EFCore中的行为,您可以在EFCore中创建数据库时手动存储模型的哈希,在启动时检查哈希,并删除并重新创建数据库(如果已更改).

To mimic the behavior in EFCore, you could manually store a hash of the model whenever you create the database in EFCore, check the hash on startup, and drop and re-create the database if it has changed.

var currentHash = MyHashingFunction(db.Model);

if (db.GetService<IRelationalDatabaseCreator>().Exists()
    && !db.Set<ModelHash>().Any(mh => mh.Value == currentHash))
{
    // Drop if changed
    db.Database.EnsureDeleted();
}

if (db.Database.EnsureCreated())
{
    // Insert hash if created
    db.Add(new ModelHash { Value = currentHash });
    db.SaveChanges();
}

这篇关于如果EF Core中的模型更改而没有迁移,则删除数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆