从数据库更新时是否保留对模型的更改? [英] Preserving changes to my models when updating from database?

查看:89
本文介绍了从数据库更新时是否保留对模型的更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用EF使用Model.context.tt模板以

I am using EF to generate my models using the Model.context.tt template as described in this post.

生成模型后,我想对模型进行一些修改。我能够做到这一点,但是我遇到的问题是,如果我从数据库更新模型,它将覆盖我所做的任何自定义。

After my models have been generated I would like to go in and make some modifications to the models. I am able to do this, but the problem that I am running into is that if I update my model from the database it will overwrite any customization that I have done.

有什么方法可以保留我对模型所做的更改,同时仍可以从数据库中进行更新?

Is there any way to preserve the changes that I have made to my models while still updating from the database?

推荐答案

在与生成的模型相同的名称空间和相同的名称空间中创建部分类,您将能够修改类,而无需在每次重新生成T4模板时更改所做的更改。

You need to create partial classes, with exactly the same name, and in the same namespace as the generated models, you will then be able to modify the class without loosing the changes each time the T4 template gets regenerated.

如果需要对原始类进行更精细的编辑,则必须编辑.tt模板。尽管我会高度建议您先检查Code First(这对于现有的数据库而言是不可能的),因为您可以完全控制类+映射。

If you need more finer tuned editing of the original class you have to edit the .tt Template. Although I would HIGHLY recommend looking into Code First (which is more than possible against an existing database) as you have full control of the class + mappings.

您可能首先复制当前生成的文件,然后将它们用作代码优先模型的基础。

You could possibly start by copying the currently generated files and using them as your basis for the code first model.

一个常见的误解是代码优先不适用于现有数据库/数据库由于名称的原因,首先工作。但这不是真的。

A common misconception is that Code First is not for Existing Database/ Database First work because of the name. But this is not true.


  • 代码优先 =编写代码并用属性或
    装饰模型

  • EDMX / Designer =使用Visual Studio设计器创建XML(.edmx),然后由T4(。)处理。 tt)模板以生成您的最终课程+上下文。 我个人觉得这种方法很痛苦,因为我经常松动更改(自定义映射/关系等)

  • 实体迁移-这是首先在这里编写代码,与上面的代码优先 方法相同,但是随后运行Migrations以生成和升级/降级数据库。

  • Code First = Writing code and decorating models with attributes or custom mappings in the Context.
  • EDMX / Designer = Using the Visual Studio designer to create an XML(.edmx) which then gets processed by a T4(.tt) template to generate your final classes + context. Personally I find this method very painful, as I constantly loose changes (custom mappings/relationships etc)
  • Entity Migrations - this is where you write your code first, identical to the "Code First" approach above, but you then run Migrations in order to generate and upgrade/downgrade a database.

这篇关于从数据库更新时是否保留对模型的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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