手动更改EF自动生成的类 [英] Keep manual changes of EF auto-generated classes

查看:95
本文介绍了手动更改EF自动生成的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您知道,当我们使用实体框架生成模型时,这些文件会自动生成,并且如果我们更改模型,则手动更改将被覆盖。

As you know, when we generate a model using the entity framework those files are automatically generated and manual changes will be overwritten if we change the model.

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

我的问题是,如何才能将这些手动更改保留在适当的位置?

My question is, how can we keep those manual changes in place?

[DataType(DataType.Date)]
[Required(ErrorMessage = "Please enter a date")]
public Nullable<System.DateTime> date { get; set; }

很难对这些类进行任何手动更改,例如上面的更改。

It's pretty hard to maintain any manual changes, like the one above, made to those classes.

您将使用哪种策略来解决此类问题?

What kind of strategy would you use to solve this kind of problem?

推荐答案

创建一个新文件,并添加一个与您生成的实体同名的部分类。

Create a new file and add a partial class with same name as your generated entity.

您可以看到示例此处。您可以在 MSDN上阅读有关分部类的更多信息。

You can see an example here. More about partial classes you can read on MSDN

比方说EF生成了下一个课程

Let's say EF generated next class

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

MetadataType(typeof(EmployeeMeta))]
public partial class Employee
{ 

}

比在您的项目中创建一个具有相同签名和相同命名空间的新文件

than in your project create a new file with same signature and same namespace

public partial class Employee
{
     //custom logic here
}

这篇关于手动更改EF自动生成的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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