如何添加验证到我的POCO(模板)班 [英] How to add validation to my POCO(template) classes

查看:203
本文介绍了如何添加验证到我的POCO(模板)班的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我用<一个href=\"http://blogs.msdn.com/b/adonet/archive/2010/01/25/walkthrough-poco-template-for-the-entity-framework.aspx\">this教程生成我的POCO类而我在我的aplication使用..问题是,我不是应该修改生成的CS文件,因为他们得到autoregenerated ......我怎么增加属性,例如[必填]之类的东西? ?请大家帮忙

So I used this tutorial to generate my poco classes which I am to use throughout my aplication.. the problem is that Im not supposed to modify the generated cs files cause they get autoregenerated... How do I add attributes like [Required] and stuff like that?? please help

推荐答案

您不能直接(除非你修改T4模板来创建它们)添加,但你可以尝试使用ASP.NET动态数据出台招。所有POCO类被定义为部分的。所以,让我们定义偏部分:

You can't add it directly (unless you modify T4 template to create them for you) but you can try to use trick introduced in ASP.NET dynamic data. All POCO classes are defined as partial. So lets define your partial part:

using System.ComponentModel.DataAnnotations;

[MetadataType(typeof(MyClassMetadata))]
public partial class MyClass
{
  private class MyClassMetadata
  {
     [Required]
     public object Id;

     [Required]
     [StringLength(100)]
     public object Name;
  }
}

元数据类是特殊类型只举行的元数据 - 这是从来没有使用过。字段名称必须相同类实际对应的字段(字段类型并不重要,所以你可以使用对象)。

在反正ASP.NET MVC您应使用专门的浏览模式每个视图和传递数据,你需要这样的验证属性将被放置在视图模型类。

Anyway in ASP.NET MVC you should use specialized View model for each view and pass data you need so the validation attributes will be placed in view model class.

这篇关于如何添加验证到我的POCO(模板)班的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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