Data Annotation
Data Annotation
- 什么是Data Annotation ?
- 如何使用 ?
- 自定义Validate Attribute
- EF Db first中使用Data Annotation
- asp.net MVC中使用Data Annotation
什么是Data Annotation ?
貌似没听过,但肯定见过
所属程序集:System.ComponentModel.DataAnnotations
DataAnnotation code:

public class Product
{ [Required]
[StringLength(10,MinimumLength =5)]
public string Name { get; set; } [Required]
public decimal? UnitPrice { get; set; }
}

没错,就是给类的属性加上描述性的验证信息,
如何使用这些信息 为我们自己所用呢?
当然是先自己想办法了,
添加辅助类:

public class ModelValidationError
{
public string FieldName { get; set; }
public string Message { get; set; }
}
public static class DataAnnotationHelper
{
public static IEnumerable<ModelValidationError> IsValid<T>(this T o)
{
var descriptor = GetTypeDescriptor(typeof(T)); foreach (PropertyDescriptor propertyDescriptor in descriptor.GetProperties())
{
var validations = propertyDescriptor.Attributes.OfType<ValidationAttribute>();
foreach (var validationAttribute in validations)
{
var v = propertyDescriptor.GetValue(o); if (!validationAttribute.IsValid(v))
{
yield return new ModelValidationError() { FieldName = propertyDescriptor.Name, Message = validationAttribute.FormatErrorMessage(propertyDescriptor.Name) };
}
}
}
}
private static ICustomTypeDescriptor GetTypeDescriptor(Type type)
{
return new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);
}
}

如何使用:

class Program
{
static void Main(string[] args)
{
Product product = new Product();
foreach (var item in product.IsValid())
{
Console.WriteLine("FieldName:{0} Error Message:{1}", item.FieldName, item.Message);
}
Console.ReadKey();
}
}

自定义ValidateAttribute
.net 提供的 ValidateAttribute不够用怎么搞?自定义呗,

public class PriceAttribute : ValidationAttribute
{
public double MinPrice { get; set; } public override bool IsValid(object value)
{
if (value == null)
{
return false;
}
var price = (double)value; if (price < MinPrice)
{
return false;
}
return true;
}
public override string FormatErrorMessage(string name)
{
return "Min Price is "+MinPrice;
}
}

使用方法和.net 提供的一样:

public class Product
{ [Required]
[StringLength(10,MinimumLength =5)]
public string Name { get; set; } [Required]
[Price(MinPrice =2)]
public decimal? UnitPrice { get; set; }
}

EF Db first中使用Data Annotation
实际应用中遇到的问题:
在使用EF DBfirst的时候,实体类的validate attribute,一不小心经常会被覆盖掉,如何解决
巧妙使用partial 类

public class ProductMetaData
{
[Required]
[StringLength(10, MinimumLength = 5)]
public string Name { get; set; } [Required]
[Price(MinPrice = 2)]
public decimal? UnitPrice { get; set; }
}
[MetadataType(typeof(ProductMetaData))]
public partial class Product
{ }
public partial class Product
{
public string Name { get; set; } public decimal? UnitPrice { get; set; }
}

asp.net mvc 中data annotation的使用:
asp.net mvc中对data annotation具有原生的支持,

Data Annotation的更多相关文章
- Data Validate 之 Data Annotation
什么是Data Annotation ? 如何使用 ? 自定义Validate Attribute EF Db first中使用Data Annotation asp.net MVC中使用Data ...
- MVC5 + EF6 + Bootstrap3 (15) 应用ModelState和Data Annotation做服务器端数据验证
Slark.NET-博客园 http://www.cnblogs.com/slark/p/mvc5-ef6-bs3-get-started-server-side-validation.html 系列 ...
- 在@Data注释lombok上使用继承警告等于/ hashCode(Warning equals/hashCode on @Data annotation lombok with inheritance)
生成equals / hashCode实现但没有调用超类,即使这个类没有扩展java.lang.Object.如果这是故意的,请将 @EqualsAndHashCode(callSuper = fal ...
- Working with Data » Getting started with ASP.NET Core and Entity Framework Core using Visual Studio » 创建复杂数据模型
Creating a complex data model 创建复杂数据模型 8 of 9 people found this helpful The Contoso University sampl ...
- spring data mongodb中,如果对象中的属性不想加入到数据库字段中
spring data mongodb中,如果对象中的属性不想加入到数据库字段中,可加@Transient注解,声明为透明属性 spring data mongodb 官网帮助文档 http://ww ...
- Spring Data MongoDB example with Spring MVC 3.2
Spring Data MongoDB example with Spring MVC 3.2 Here is another example web application built with S ...
- Spring Data Elasticsearch
项目清单 elasticsearch服务下载包括其中插件和分词 http://download.csdn.net/detail/u014201191/8809619 项目源码 资源文件 ...
- WPF中使用Data Annotations验证Model
.NET Framework中System.ComponentModel.DataAnnotations提供了很多属性来验证对象的属性.可以在C:\Program Files (x86)\Refere ...
- Spring Data 整合 ElasticSearch搜索服务器
一.基于 maven 导入坐标(pom.xml文件) <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi ...
随机推荐
- Android ScrollView嵌套HorizontalScrollView 滑动问题 ScrollView包括GridView显示问题
今天项目使用到ScrollView嵌套HorizontalScrollView,ScrollView里包括GridView,发现几个问题非常经典.在此记录: 问题1.ScrollView嵌套Horiz ...
- android项目 之 记事本(6)----- 加入手写
想必大家都用过QQ的白板功能,里面主要有两项,一个是涂鸦功能,事实上类似于上节的画板功能,而还有一个就是手写,那记事本怎么能没有这个功能呢,今天就来为我们的记事本加入手写功能. 先上图,看看效果: 看 ...
- poj2486 Apple Tree【区间dp】
转载请注明出处,谢谢:http://www.cnblogs.com/KirisameMarisa/p/4374766.html ---by 墨染之樱花 [题目链接]http://poj.org/p ...
- DevExpress ASP.NET 使用经验谈(8)-ASPxGridView自定义列和基本事件
为演示本节示例,我们在原来Users表增加[性别Gender].[兴趣爱好Hobbies],[CreateTime创建时间],[ModifyTime]修改时间这4个字段, ALTER TABLE [d ...
- Nginx 之六: Nginx服务器的反向代理功能
一:Nginx作为正向代理服务器: 1.正向代理:代理(proxy)服务也可以称为是正向代理,指的是将服务器部署在公司的网关,代理公司内部员工上外网的请求,可以起到一定的安全作用和管理限制作用,正向代 ...
- python实现单向链表
#Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self ...
- C# 操作Excel (二)
根据翻阅LTP.Net知识库系列之四中Office操作功能: 一.记录常用如下 (1)“在自己的程序中宿主Office”的意思就是在我们自己开发的应用程序的窗体上,显示一个就像Office应用程序那样 ...
- CoreAnimation —— CALayer
概述 如上篇博文讲述,UIView中封装了很多系统方法,可以满足我们的大部分需求.但是,其也有很多限制.那些方法产生的动画基本单元为UIView,是非常重量级的对象,而且也不支持三维布局,大部分是对视 ...
- 【Web】java date 到 Oracle date 精确到时分秒
有两种方法: java.util.Date startTime=new Date("2014/01/01 23:00:00"); 1.new Timestamp(startTime ...
- [转] 8张图学习javascript
学习的道路就是要不断的总结归纳,好记性不如烂笔头,so,下面将po出8张javascript相关的思维导图. 思维导图小tips:思维导图又叫心智图,是表达发射性思维的有效的图形思维工具 ,它简单却又 ...