我有一个现有的大型数据库要通信,并且我首先使用的是EF 5.0数据库,所以我遇到的问题是,如果我在类上创建诸如[stringlength(50)]
的任何数据修饰,然后在“从数据库上传”中的所有数据注释均已消失。我该怎么做才能保留它们?
最佳答案
很简单:不能! 因为这些代码是自动生成的,并且在每次更新或更改模型时都会被覆盖。
但是,您可以通过扩展模型来实现所需的功能。假设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)生成的实体类和您的类的 namespace 必须相同-这里为
YourSolution
。2)您的第一个类必须为
partial
,并且其名称必须与EF生成的类相同。经历这个过程,您的属性再也不会丢失...
关于asp.net-mvc-4 - 从数据库上传模型时丢失dataAnottation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17744625/