初始支架后,实体框架核心数据库优先更新? [英] Entity Framework Core Database-First Update after initial Scaffold?

查看:76
本文介绍了初始支架后,实体框架核心数据库优先更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Entity Framework Core,并且一直在致力于实现数据库优先应用程序。初始的Scaffold-DbContext命令可以正常工作,并且可以正确创建我的所有实体(如果没有按照我的意愿进行组织)。这是一个SQL Server数据库,它使用模式来分解职责范围,而我完全不在乎Scaffold只是将它们全部放入一个文件夹中。

I'm playing around with Entity Framework Core and I have been working on implementing a Database-First application. The initial Scaffold-DbContext command works just fine and creates all my entities correctly, if not organized as I would like. It's a SQL Server database that uses schemas to break up areas of responsibility and I don't really care for the fact that the Scaffold just throws them all into a single folder.

此外,我无法确定是否有一种方法可以在数据库更新发生后重新运行Scaffold来更新类。我能找到的最接近的是使用-force参数重新运行Scaffold-DbContext命令。但是,这也会覆盖我添加到Context.cs文件中的所有自定义代码,例如将连接字符串指向配置值而不是硬编码。

That aside, I have been unable to determine if there is a way to re-run the Scaffold to update the classes after a database update has occurred. The closest I can find is to re-run the Scaffold-DbContext command with the -force parameter. However, this also overwrites any custom code I have added to the Context.cs file, like pointing the connection string to a config value instead of hard-coding.

看着与这个问题类似的其他几个问题,但仅讨论初始支架,而不涉及进一步的更新。

I have looked at a couple other questions similiar to this one, but it only talks about the initial scaffold, not further updates.

是否有办法手动编码任何将来的更改来做到这一点?否则,使用EF Core似乎使数据库优先方法完全毫无用处。

Is there a way short of manually coding any future changes to do this? Without that it seems to make a database-first approach utterly worthless with EF Core.

推荐答案

就像您自己说的那样...数据库优先方法的主要问题:永远不要手动更改模型并开始重命名等。除非您100%确保数据库不会再更改。如果不确定100%,则只需使用自动生成的模型进行编码。

Like you said yourself... The main problem with database first approach : You should never change the model manually and start renaming things etc. Except if you are 100 % sure that your database won't change anymore. If you'r not 100 % sure, just code with the model that has been auto-generated.

重新脚手架将覆盖直接在模型类中进行的所有更改,

Re-Scaffolding will overwrite any changes made directly in the model class, erasing all what you have changed or added.

但是您可以在局部类中创建不会被自动映射覆盖的部分类:

But you can make partial classes on the side that won't be overwritten by auto mapping :

public partial class TableName
{
    public string Name_of_a_property
    {get; set;}
}

这是在确保实体代码安全的同时增加代码的一种好方法自动映射不会影响它。只需确保部分视图与自动生成的类具有相同的名称,并且一切都可以。

It's a nice way to add code to your entity while being sure it won't be touched by auto-mapping. Just make sure the partial view has the same name as the auto-generated class and everything should be OK.

这篇关于初始支架后,实体框架核心数据库优先更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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