在使用EF Core开发期间如何处理数据库更改? [英] How to deal with database changes during development with EF Core?

查看:617
本文介绍了在使用EF Core开发期间如何处理数据库更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用.NET Core和Entity Framework Core开发期间,我正在为数据库更改而苦苦挣扎.

I am struggling with database changes during development with .NET Core and Entity Framework Core.

当我创建新模型并将其添加到dbContext时,即使在Startup.cs中使用dbContext.Database.EnsureCreated();,它也不会创建新表.

When I create new model and add it to dbContext, even with dbContext.Database.EnsureCreated(); in Startup.cs it does not create new tables.

只有在我之前做过dotnet ef database drop的情况下,它才会创建所有表,但是每次添加新模型都必须为db播种是很烦人的. 每次创建越来越多的迁移对我来说都不是一个好主意...

It will create all tables only if I will do dotnet ef database drop before, but it is pretty annoying to have to seed db every time adding new model. creating more and more migration every time does not look like good idea to me...

有人可以建议更好的方法吗?

Can someone suggest better way?

推荐答案

不幸的是,似乎EF核心不像EF 6中那样支持自动迁移.这意味着您必须为每个更改添加一个新迁移.您可以在Startup => Configure中添加此代码以自动应用最新的迁移,但是如果我了解他们的文档说明,则必须为每次更改添加一个新的迁移.

Unfortunately it seems that EF core does not support automatic migrations like in EF 6. This means for every change you have to add a new migration. You can in your Startup => Configure add this code to automatically apply the latest migration but if i understand their documentation right you have to add a new migration for every change.

        using (var serviceScope app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<YourDbContext>();
            context.Database.Migrate();
        }

参考: EntityFramework核心自动迁移 https://github.com/aspnet/EntityFrameworkCore/issues/6214

也同意@Nathan关于使用流畅的api自己创建结构的想法.

Also agree with @Nathan about creating the structure yourself with fluent api.

希望这会有所帮助.

这篇关于在使用EF Core开发期间如何处理数据库更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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