将DataAnnotations与实体框架一起使用

时间:2010-06-08 17:59:58

标签: c# entity-framework validation asp.net-mvc-2

我在VS2010中使用了Entity Framework来创建一个包含属性,firstName,lastName和email的简单person类。如果我想像在blog post中那样附加DataAnnotations,我会遇到一个小问题,因为我的person类是动态生成的。我可以直接编辑动态生成的代码,但每当我必须更新我的模型时,我的所有验证代码都会被删除。

第一直觉是创建一个部分类并尝试附加注释,但它抱怨我正在尝试重新定义属性。我不确定你是否可以在C#中使用C ++中的函数声明来进行属性声明。如果可能,那可能就是答案。这是我尝试过的片段:

namespace PersonWeb.Models
{
  public partial class Person
  {
    [RegularExpression(@"(\w|\.)+@(\w|\.)+", ErrorMessage = "Email is invalid")]
    public string Email { get; set; } 
    /* ERROR: The type 'Person' already contains a definition for 'Email' */
  }
}

2 个答案:

答案 0 :(得分:24)

伙伴类或多或少是你的代码片段旅行的方向,除了你的手动编码的部分Person类将有一个内部类,如:

[MetadataType(typeof(Person.Metadata))]
public partial class Person {
    private sealed class MetaData {
        [RegularExpression(...)]
        public string Email { get; set; }
    }
}

或者您可以拥有手动部分Person类和单独的Meta类,如:

[MetadataType(typeof(PersonMetaData))]
public partial class Person { }

public class PersonMetaData {
[RegularExpression(...)]
public string Email;
}

这些是变通方法,并且具有映射的Presentation类可能更合适。

答案 1 :(得分:3)

您需要使用元数据“好友”类或(我的偏好)project onto a presentation model instead of binding views directly to entities