在实体框架中使用 DataAnnotations [英] Using DataAnnotations with Entity Framework
问题描述
我使用 VS2010 的实体框架创建了一个简单的人员类,其中包含属性、名字、姓氏和电子邮件.如果我想附加 DataAnnotations 就像在这个 博客文章 我有一个小问题,因为我的 person 类是动态生成的.我可以直接编辑动态生成的代码,但任何时候我必须更新我的模型,我的所有验证代码都会被清除.
I have used the Entity Framework with VS2010 to create a simple person class with properties, firstName, lastName, and email. If I want to attach DataAnnotations like as is done in this blog post I have a small problem because my person class is dynamically generated. I could edit the dynamically generated code directly but any time I have to update my model all my validation code would get wiped out.
第一直觉是创建一个部分类并尝试附加注释,但它抱怨我正在尝试重新定义该属性.我不确定您是否可以像 C++ 中的函数声明一样在 C# 中进行属性声明.如果可以,那可能就是答案.这是我尝试过的片段:
First instinct was to create a partial class and try to attach annotations but it complains that I'm trying to redefine the property. I'm not sure if you can make property declarations in C# like function declarations in C++. If you could that might be the answer. Here's a snippet of what I tried:
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' */
}
}
推荐答案
伙伴类或多或少是您的代码片段前进的方向,除非您手动编码的部分 Person 类会有一个内部类,例如:
A buddy class is more or less the direction your code snippet is journeying, except your manually coded partial Person class would have an inner class, like:
[MetadataType(typeof(Person.Metadata))]
public partial class Person {
private sealed class MetaData {
[RegularExpression(...)]
public string Email { get; set; }
}
}
或者你可以手动创建部分 Person 类和一个单独的 Meta 类,例如:
Or you could have your manually partial Person class and a separate Meta class like:
[MetadataType(typeof(PersonMetaData))]
public partial class Person { }
public class PersonMetaData {
[RegularExpression(...)]
public string Email;
}
这些是变通方法,使用映射的 Presentation 类可能更合适.
These are workarounds and having a mapped Presentation class may be more suitable.
这篇关于在实体框架中使用 DataAnnotations的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!