使用DataAnnotations与实体框架 [英] Using DataAnnotations with Entity Framework
问题描述
我已经使用VS2010的实体框架来创建一个简单的人物类,其中包含属性firstName,lastName和email。如果我想附加DataAnnotations,就像在这个 blog post 我有一个小问题,因为我的人类是动态生成的。我可以直接编辑动态生成的代码,但任何时候我必须更新我的模型,所有的验证码将被清除。
第一本能就是创建一个部分类,尝试附加注释,但它抱怨我正在尝试重新定义属性。我不知道您是否可以在C#中使用C ++中的函数声明来创建属性声明。如果可能的话可能是答案。以下是我尝试的代码片段:
命名空间PersonWeb.Models
{
public partial class Person
{
[RegularExpression(@(\w | \。)+ @(\w | \。)+,ErrorMessage =电子邮件无效)]
public string Email {get;组; }
/ *错误:类型'Person'已经包含'Email'的定义* /
}
}
一个好友类或多或少是您的代码片段的方向,除了您的手动编码的部分Person类将有一个内部类,如:
[MetadataType(typeof(Person.Metadata))]
public partial class Person {
私密密码类MetaData {
[RegularExpression(...)]
public string Email {get;组;
}
}
或者您可以手动部分Person类和一个单独的Meta类,如:
[MetadataType(typeof(PersonMetaData))]
public partial class Person {}
public class PersonMetaData {
[RegularExpression(...)]
public string Email;
}
这些是解决方法,并且映射的Presentation类可能更合适。 p>
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.
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' */
}
}
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; }
}
}
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;
}
These are workarounds and having a mapped Presentation class may be more suitable.
这篇关于使用DataAnnotations与实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!