这很简单:你不能!因为这些代码是自动生成的,并且会在每次模型更新或更改时被覆盖。
但是,您可以通过扩展模型来实现您所需要的。假设 EF 为您生成了以下实体类:
namespace YourSolution
{
using System;
using System.Collections.Generic;
public partial class News
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int UserID { get; set; }
public virtual UserProfile User{ get; set; }
}
}
并且您想要做一些工作来保留您的数据注释和属性。所以,请按照以下步骤操作:
首先,在某个位置(任何你想要的地方,但最好是在Models)添加两个类,如下所示:
namespace YourSolution
{
[MetadataType(typeof(NewsAttribs))]
public partial class News
{
// leave it empty.
}
public class NewsAttribs
{
// Your attribs will come here.
}
}
然后将您想要的属性和属性添加到第二个类 - NewsAttribs 这里。 :
public class NewsAttrib
{
[Display(Name = "News title")]
[Required(ErrorMessage = "Please enter the news title.")]
public string Title { get; set; }
// and other properties you want...
}
注意事项:
1) 生成的实体类的命名空间和你的类必须相同 - 这里是YourSolution。
2) 您的第一个类必须为partial,并且其名称必须与 EF 生成的类相同。
通过这个,你的属性再也不会丢失了......