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<=0);
}
return validResult;
}
}
}

在实体中使用方法如下:

        /// <summary>
/// 类别代码
/// </summary>
[Required()]
[MaxLength(50)]
[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[0].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 > 0)
{
returnAttrs = attrs.Select(t => t as TAttribute).ToArray();
return true;
}
returnAttrs=null;
return false;
}
}

实现UniqueAttribute唯一性约束,sqlunique约束[转]的更多相关文章

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

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

  2. MySQL进阶13--常见六大约束: 非空/默认/主键/唯一约束/检查约束/外键约束--表级约束 / 列级约束

    /* MySQL进阶13 常见六大约束: 1.not null 非空 2.default :默认值,用于保证该字段的默认值 ; 比如年龄:1900-10-10 3.primary key : 主键,用 ...

  3. oracle 删除外键约束 禁用约束 启用约束

    oracle 删除外键约束 禁用约束 启用约束 执行以下sql生成的语句即可 删除所有外键约束 Sql代码  select 'alter table '||table_name||' drop con ...

  4. 实现UniqueAttribute唯一性约束

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

  5. 松软科技课堂:SQL--UNIQUE约束

    SQL UNIQUE 约束(文章来源:松软科技-www.sysoft.net.cn-) UNIQUE 约束唯一标识数据库表中的每条记录. UNIQUE 和 PRIMARY KEY 约束均为列或列集合提 ...

  6. 分享知识-快乐自己:MySQL中的约束,添加约束,删除约束,以及一些其他修饰

    创建数据库: CREATE DATABASES 数据库名: 选择数据库: USE 数据库名: 删除数据库: DROP DATAVBASE 数据库名: 创建表: CREATE TABLE IF NOT ...

  7. MySQL中的约束,添加约束,删除约束,以及其他修饰

    一.NOT NULL(非空约束)添加非空约束 1)建表时直接添加 CREATE TABLE t_user(user_id INT(10) NOT NULL); 2)通过ALTER 语句 ALTER T ...

  8. XML约束——Schema约束

    XML Schema 也是一种用于定义和描述 XML 文档结构与内容的模式语言,其出现是为了克服 DTD 的局限性 XML Schema VS DTD: •XML Schema符合XML语法结构. • ...

  9. XML约束——DTD约束

    参考: 方立勋老师的讲课视频.   什么是XML约束 •在XML技术里,可以编写一个文档来约束一个XML文档的书写规范,这称之为XML约束. 为什么需要XML约束 常用的约束技术 •XML DTD • ...

随机推荐

  1. Linux and the Device Tree

    来之\kernel\Documentation\devicetree\usage-model.txt Linux and the Device Tree ----------------------- ...

  2. Apache配置文件讲解

        持续作用扩展自 HTTP/1.0 和 HTTP/1.1 的长连接特性.提供了长效的 HTTP 会话,用以在同 一个 TCP 连接中进行多次请求. 在某些情况下, 这样的方式会对包含大量图片的 ...

  3. blue and red ball

    #include<iostream> #include<cstring> using namespace std; int sum; ]; int n; int head; i ...

  4. SLES 10安装Oracle10gR2笔记

    SLES 10安装Oracle10gR2笔记 一. 数据库安装 . 安装C/C++ Compiler gcc --version验证是否安装 . 验证Service Pack版本 SPident –v ...

  5. Android SDK Tools 更新

    C:\WINDOWS\system32\drivers\etc\hosts 文件用记事本打开后 添加下面的 74.125.237.1 dl-ssl.google.com

  6. ASP.NET中cookie与Fiter实现简单登陆,AllowAnonymous匿名登陆

    向服务器发送cookie 在登陆的时候,我们可以可以通过下列代码,向服务器发送cookie,其中包括自己的账号信息(不涉及加密),用以后面判断访问者. HttpCookie cookie = new ...

  7. set集合(set是一个无序且不重复的元素集合)

    功能: 一.可以去掉列表,元组中的重复项 二.可以求交集,合集,差集等 def add(self, *args, **kwargs): """ 添加 "&quo ...

  8. 详解MVC设计模式

    1 MVC介绍 众所周知MVC不是设计模式,是一个比设计模式更大一点的模式,称作设计模式不合理,应该说MVC它是一种软件开发架构模式,它包含了很多的设计模式,最为密切是以下三种:Observer (观 ...

  9. CSS选择器详解

    选择器是CSS的核心,从最初的元素.class/id选择器,演进到伪元素.伪类,以及CSS3中提供的更丰富的选择器,定位页面上的任意元素开始变得愈发的简单. 1.元素选择器 这是最基本的CSS选择器, ...

  10. JAVA 1.8 理解面向对象程序设计

    1. break语句:经常用在循环语句中,用于跳出整个循环,执行循环后面的代码. 2. continue语句:经常用在循环语句中,用于跳出当前的这个循环(或者是跳出本次循环),开始下一次循环的执行. ...