使用DataAnnotations实体框架 [英] Using DataAnnotations with Entity Framework

查看:142
本文介绍了使用DataAnnotations实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Entity Framework和Visual Studio 2010创建具有的属性,名字,姓氏,和电子邮件一个简单的人类。如果我要附加DataAnnotations作为一样在此做的博客文章我有一个小问题,因为是动态生成的我一个人的类。我可以直接编辑动态生成code,但任何时候,我需要更新我的模型我所有的验证code将得到一扫而光。

第一反应是创建一个部分类,并尝试附加注释,但抱怨我试图重新定义属性。我不知道,如果你可以在C#像C ++函数声明作出财产申报。如果你可以,可能是答案。这里是什么我想一个片段:

 命名空间PersonWeb.Models
{
  公共部分类人
  {
    [RegularEx pression(@(\\ W | \\)+ @(\\ W | \\)+的ErrorMessage =电子邮件无效)]
    公共字符串电子邮件{获得;组; }
    / *错误:类型人已经包含了电子邮件* /定义
  }
}


解决方案

一个哥们类是多还是少你的code片断痴痴,除非你手动codeD部分Person类将有一个内部类的方向,如:

  [MetadataType(typeof运算(Person.Metadata))]
公共部分类Person {
    私人密封类的元数据{
        [RegularEx pression(...)
        公共字符串电子邮件{获得;组; }
    }
}

或者你可以有你的手工部分Person类和一个独立元类,如:

  [MetadataType(typeof运算(PersonMetaData))]
公共部分类Person {}公共类PersonMetaData {
[RegularEx pression(...)
公共字符串的电子邮件;
}

这是变通方法,并有一个映射presentation类可能更适合。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆