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 ...
随机推荐
- 编写可维护的JavaScript—语句和表达式&变量、函数和运算符
语句和表达式 所有的块语句都应当使用花括号.包括: if for while do…while… try…catch…finally //不好的写法 if (condition) doSomethin ...
- Oracle表解锁
网搜 --第一步 查看被锁表 select b.owner,b.object_name, b.object_id,l.session_id,l.locked_mode from v$locked_ob ...
- 【原】Spring和Dubbo整合案例和过程
Dubbo是Alibaba开源的分布式服务框架,它最大的特点是按照分层的方式来架构,使用这种方式可以使各个层之间解耦合(或者最大限度地松耦合).从服务模型的角度来看,Dubbo采用的是一种非常简单的模 ...
- Oracle数据库的安装详解
1.写在安装前的话 可能有很多的菜鸟十分害怕大型软件的安装,因为安装过程中的一些错误很让他们头疼.下面我就写一个教程,希望能对大家有帮助,在安装ORACLE之前给大家一点点的意见: (1)尽量要安装L ...
- 解决servlet乱码问题
1) request中的中文乱码 a) POST方式提交 在获得提交表单信息之前调用request.setCharactersEncoding("UTF-8"); b) GET方式 ...
- Centos6 安全防护设置指南
参考博文: Centos 6.4安全防护设置指南 4.使用chattr命令给下列文件加上不可更改的属性 有效防止非法用户进行文件的修改. [root@localhost ~]# chattr +i / ...
- C# DES对称加密解密
/// <summary> /// 加密 /// </summary> /// <param name="str"></param> ...
- Open vswitch 之Qos rate-limiting 原理
Openvswitch之Qos rate-limiting原理 OVS的qosrate-limiting功能是采用令牌桶(Token-Bucket)机制进行的.这里的“令牌桶”是指网络设备的内部存储池 ...
- ssh连接Linux自动断开后再也无法连上的问题
近期公司测试机有点抓狂,情况是这样的:用SSH登录后正常使用,但另外一部电脑也在登录,这时候会发生全部断开的情况,再也无法连接,连IP都PING不通. 今天尝试在/etc/hosts.deny 加入如 ...
- linux命令--sysctl
sysctl sysctl被用来在执行时配置内核参数.这些参数都存储在/proc/sys/(以键-值对形式存储)中.你可以用sysctl来读和写数据 命令参数 variable 要读的键值的名字 ...