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 ...
随机推荐
- RGB与HSB之间的转换公式
先来了解一些概念: 1.RGB是一种加色模型,就是将不同比例的Red/Green/Blue混合在一起得到新颜色.通常RGB颜色模型表示为: 2.HSB(HSV) 通过色相/饱和度/亮度三要素来表达颜色 ...
- java--折半查找
/* 折半查找 */ class TwoSearch { //折半查找可以提高效率,但必须得保证是有序的数组 public static int halfSearch(int[] arr,int ke ...
- python下yield(生成器)
python下的协程: #encoding=utf-8 """ 协程----微小的进程 yield生成器-----生成一个可迭代对象比如list, tuple,dir 1 ...
- runtime的概念,message send如果寻找不到相应的对象,如何进行后续处理
运行时刻是指一个程序在运行(或者在被执行)的状态.也就是说,当你打开一个程序使它在电脑上运行的时候,那个程序就是处于运行时刻.在一些编程语言中,把某些可以重用的程序或者实例打包或者重建成为“运行库”. ...
- 在mac本上折腾android 开发环境
众所周知的原因,google的很多网站在国内无法访问,苦逼了一堆天朝程序员,下是在mac本上折腾android 开发环境的过程: 一.先下载android sdk for mac 给二个靠谱的网址: ...
- CheckBox控件实现选项的选中
1:设置控件属性 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xml ...
- The Power of Reading——英语学习小技巧之七
This method is "The Power of Reading" and it comes from an article by Dr.Stephen Krashen. ...
- JS 控制 form是否提交表单
问题背景:用php删除数据,希望在点击“删除”(button)的时候JS弹出confirm来确认是否删除. 此段代码为php中的form: <form action="?form=de ...
- PHP学习笔记14-操作session
PHP会话管理图: 创建index: <?php /** * Created by PhpStorm. * User: Administrator * Date: 2015/7/2 * Time ...
- 入门前端之HTML
本文内容: HTML概念 HTML元素 HTML属性 HTML标题 HTML段落 HTML格式化 HTML样式 HTML 链接 HTML 图像 HTML 表格 HTML 列表 HTML 块 HTML ...