using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity; namespace Zwj.TEMS.Base
{
/// <summary>
/// 唯一性标识
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class UniqueAttribute : ValidationAttribute
{
protected string tableName;
protected string filedName; public UniqueAttribute(string tableName, string filedName)
{
this.tableName = tableName;
this.filedName = filedName;
} public override Boolean IsValid(Object value)
{
bool validResult = false;
//TEMSContext 是我项目中的DB上下文类,若需要使用在其它项目中,请更改成实际的DB上下文类就可以了!
using (TEMSContext context = new TEMSContext())
{
string sqlCmd=string.Format("select count(1) from [{0}] where [{1}]=@p0",tableName,filedName);
context.Database.Connection.Open();
var cmd=context.Database.Connection.CreateCommand();
cmd.CommandText = sqlCmd;
var p0 = cmd.CreateParameter();
p0.ParameterName = "@p0";
p0.Value = value;
cmd.Parameters.Add(p0);
int result=Convert.ToInt32(cmd.ExecuteScalar());
validResult=(result<=);
}
return validResult;
}
}
}

在实体中使用方法如下:

        /// <summary>
/// 类别代码
/// </summary>
[Required()]
[MaxLength()]
[Unique("Category", "CategoryCode")]
[Display(Name = "类别代码")]
public string CategoryCode { get; set; }

调用与验证方法如下:

//我这里写了一个单元测试的验证方法,大家可以用在实际项目中
public void ValidateEntity(object entity)
{
var t = entity.GetType();
var properties = t.GetProperties();
foreach (var p in properties)
{
UniqueAttribute[] attrs;
if (p.TryGetAttribute<UniqueAttribute>(out attrs))
{
bool result = attrs[].IsValid(p.GetValue(entity, null));
Assert.IsTrue(result, "验证不唯一,存在重复值!");
}
}
}

    public static class ClassExtension
{
/// <summary>
/// 尝试获取指定类别特性
/// </summary>
/// <typeparam name="TAttribute"></typeparam>
/// <param name="p"></param>
/// <param name="returnAttrs"></param>
/// <returns></returns>
public static bool TryGetAttribute<TAttribute>(this PropertyInfo p, out TAttribute[] returnAttrs) where TAttribute : Attribute
{
var attrs = p.GetCustomAttributes(typeof(TAttribute), false);
if (attrs != null && attrs.Length > )
{
returnAttrs = attrs.Select(t => t as TAttribute).ToArray();
return true;
}
returnAttrs=null;
return false;
}
}



以下是博客园的相关文章,他主要描述的是如何在数据库中生成唯 一性索引,而对如何在C#进行唯一性验证并没有说明,我这篇文章仅作一个补充。

如何在EF CodeFirst中使用唯一约束(Unique)

实现UniqueAttribute唯一性约束的更多相关文章

  1. 实现UniqueAttribute唯一性约束-优化版

    我之前就写过一篇<实现UniqueAttribute唯一性约束>,虽然实现了通过调用IsValid方法可以进行唯一性验证,但有一个缺点,那就是耦合度过高,原因是里面的DB上下文对象是直接写 ...

  2. 实现UniqueAttribute唯一性约束,sqlunique约束[转]

    using System; using System.ComponentModel.DataAnnotations; using System.Data.Entity; namespace Zwj.T ...

  3. Constraint1:主键约束,唯一性约束和唯一索引

    1,主键约束创建索引 作为Primay Key的列是唯一的,非空的,Sql Server在创建主键约束时,自动为主键列创建一个唯一索引,并且索引列不允许为null. create table dbo. ...

  4. sqlserver2005唯一性约束

    [转载]http://blog.163.com/rihui_7/blog/static/21228514320136193392749/ 1.设置字段为主键就是一种唯一性约束的方法,如   int p ...

  5. mysql主键约束和唯一性约束

    主键约束和唯一性约束都是索引,它们的区别是: 主键字段可以确保唯一性,但主键字段不能为NULL. 唯一性约束可以确保唯一性,但唯一性约束的字段可以为NULL 唯一性约束对含有NULL的记录不起作用,即 ...

  6. Oracle中主键、外键、索引、序列、唯一性约束的创建

    1.主键的创建 方法一:直接在sql语句中声明字段主键约束 create table table_name (id type[length] constraint pk_name primary ke ...

  7. Mysql 唯一性约束添加

    来自:  http://blog.csdn.net/yumushui/article/details/38960619 一.单列唯一约束 在一列上添加唯一约束,主要是让该列在表中只能有唯一的一行,例如 ...

  8. Oracle之唯一性约束(UNIQUE Constraint)使用方法具体解释

    Oracle | PL/SQL唯一索引(Unique Constraint)使用方法 1 目标 用演示样例演示怎样创建.删除.禁用和使用唯一性约束. 2 什么是唯一性约束? 唯一性约束指表中一个字段或 ...

  9. Odoo中如何复制有唯一性约束的记录?

    转载请注明原文地址:https://www.cnblogs.com/cnodoo/p/9281393.html  如果为模型的字段添加了唯一性约束,那么在记录的form视图功能菜单上选择“复制”时就会 ...

随机推荐

  1. 【腾讯Bugly干货分享】微信读书iOS性能优化

    本文来自于腾讯bugly开发者社区,非经作者同意,请勿转载,原文地址:http://dev.qq.com/topic/578c93ca9644bd524bfcabe8 “8小时内拼工作,8小时外拼成长 ...

  2. EF6(CodeFirst)+MySql开发脱坑指南

    废话 话说当年,在一个春光明媚的晌午,邂逅了迷人的丁香姑娘,从此拜倒在了她的石榴裙下,至今不能自拔,这位丁香姑娘就是ORM思想. 所谓ORM思想,我的理解就是根据一定的规则,把程序中的对象和数据库中的 ...

  3. 冲刺阶段 day13

    ---恢复内容开始--- 项目进展 今天星期三,我们将专业管理部分又继续做了完善,之前漏掉的几项功也一一补全,没能实现的数据库部分也已经进行了完善,并且对已经完成的部分进行了检测,数据库的部分还有待进 ...

  4. java提高篇(二九)-----Vector

    在java提高篇(二一)-–ArrayList.java提高篇(二二)-LinkedList,详细讲解了ArrayList.linkedList的原理和实现过程,对于List接口这里还介绍一个它的实现 ...

  5. 了解了这些才能开始发挥jQuery的威力

    由于当前jQuery如此的如雷贯耳,相信不用介绍什么是jQuery了,公司代码中广泛应用了jQuery,但我在看一些小朋友的代码时发现一个问题,小朋友们使用的仅仅是jQuery的皮毛,只是使用id选择 ...

  6. LuaAlchemy API 介绍

    The AS3 Sugar provides a Lua-like way to access AS3 class and instance creation, property getter/set ...

  7. Linux网络编程系列-TCP编程实例

    实例: client #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #inc ...

  8. CSS的两个小知识点 伪类选择器和display:table-cell

    li:first-child {color:red} li:nth-child(3n) {color: red} 在对nth-child传参的时候,已经直接用公式,3n就表示3的倍数.多用伪类和伪元素 ...

  9. oracle 表类型变量的使用

    转载于:http://www.itxuexiwang.com/a/shujukujishu/oracle/2016/0216/89.html?1455872314 使用记录类型变量只能保存一行数据,这 ...

  10. Linux~centos上安装.netcore,HelloWorld归来!

    对于跨平台的.netCore来说,让它的程序运行在Linux系统上已经成为必然,也是一种趋势,毕竟我们的很多服务都放在linux服务器上(redis,mongodb,myql,fastDFS,luce ...