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 ...
随机推荐
- bootstrap固定响应式导航
<link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.2.0/css/bootstrap. ...
- jacksonall的使用,解析json
转自:http://www.cnblogs.com/lee0oo0/archive/2012/08/23/2652751.html , Jackson可以轻松的将Java对象转换成json对象和xml ...
- python2.7_1.13_编写一个SNTP客户端
1.pip install ntplib 2.思路:先创建一个NTPClient实例,然后在这个实例上调用request()方法,把NTP服务器的地址传入方法,向NTP服务器发起一个NTP请求,响应使 ...
- gdb调试相关
GDB调试及其调试脚本的使用返回脚本百事通一.GDB调试 1.1. GDB 概述 GDB是GNU开源组织发布的一个强大的UNIX下的程序调试工具.或许,各位比较喜欢那种图形界面方式的,像VC.BCB等 ...
- DELPHI编写服务程序总结
DELPHI编写服务程序总结 一.服务程序和桌面程序的区别 Windows 2000/XP/2003等支持一种叫做“系统服务程序”的进程,系统服务和桌面程序的区别是:系统服务不用登陆系统即可运行:系统 ...
- hibernate 缓存 4.3
缓存在hibernate中是天生就有的,是一级缓存,当session关闭时一级缓存就失效了 一级缓存是内置的,生效范围是在同一个session中才行.二级缓存是需要配置才有 判断当前项在不在一级缓存中 ...
- cocos2d-x 通过JNI实现c/c++和Android的java层函数互调
文章摘要: 本文主要实现两个功能: (1)通过Android sdk的API得到应用程序的包名(PackageName),然后传递给c++层函数. (2)通过c++函数调用Android的java层函 ...
- 2013杭州网络赛C题HDU 4640(模拟)
The Donkey of Gui Zhou Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/O ...
- uva-11995 - I Can Guess the Data Structure!(栈,优先队列,队列,水题)
11995 - I Can Guess the Data Structure! There is a bag-like data structure, supporting two operation ...
- XMPP个人信息展示
在现阶段的通信服务中.各种标准都有,因此会出现无法实现相互连通,而XMPP(Extensible Message and presence Protocol)协议的出现.实现了整个及时通信服务协议的互 ...