保留EF自动生成类的手动更改

本文关键字:EF 自动生成 保留 | 更新日期: 2023-09-27 18:10:35

正如您所知,当我们使用实体框架生成模型时,这些文件是自动生成的,如果我们更改模型,手动更改将被覆盖。

//------------------------------------------------------------------------------
// <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>
//------------------------------------------------------------------------------

我的问题是,我们如何保持这些手工更改的位置?

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

要维护像上面那样对这些类所做的任何手动更改是相当困难的。

你会用什么策略来解决这种问题?

保留EF自动生成类的手动更改

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

你可以在这里看到一个例子。关于分部类的更多信息,可以在MSDN

上阅读。

假设EF生成下一个类

//------------------------------------------------------------------------------
// <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
{ 
}

创建一个具有相同签名和相同命名空间的新文件

public partial class Employee
{
     //custom logic here
}