实现UniqueAttribute唯一性约束
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唯一性约束的更多相关文章
- 实现UniqueAttribute唯一性约束-优化版
我之前就写过一篇<实现UniqueAttribute唯一性约束>,虽然实现了通过调用IsValid方法可以进行唯一性验证,但有一个缺点,那就是耦合度过高,原因是里面的DB上下文对象是直接写 ...
- 实现UniqueAttribute唯一性约束,sqlunique约束[转]
using System; using System.ComponentModel.DataAnnotations; using System.Data.Entity; namespace Zwj.T ...
- Constraint1:主键约束,唯一性约束和唯一索引
1,主键约束创建索引 作为Primay Key的列是唯一的,非空的,Sql Server在创建主键约束时,自动为主键列创建一个唯一索引,并且索引列不允许为null. create table dbo. ...
- sqlserver2005唯一性约束
[转载]http://blog.163.com/rihui_7/blog/static/21228514320136193392749/ 1.设置字段为主键就是一种唯一性约束的方法,如 int p ...
- mysql主键约束和唯一性约束
主键约束和唯一性约束都是索引,它们的区别是: 主键字段可以确保唯一性,但主键字段不能为NULL. 唯一性约束可以确保唯一性,但唯一性约束的字段可以为NULL 唯一性约束对含有NULL的记录不起作用,即 ...
- Oracle中主键、外键、索引、序列、唯一性约束的创建
1.主键的创建 方法一:直接在sql语句中声明字段主键约束 create table table_name (id type[length] constraint pk_name primary ke ...
- Mysql 唯一性约束添加
来自: http://blog.csdn.net/yumushui/article/details/38960619 一.单列唯一约束 在一列上添加唯一约束,主要是让该列在表中只能有唯一的一行,例如 ...
- Oracle之唯一性约束(UNIQUE Constraint)使用方法具体解释
Oracle | PL/SQL唯一索引(Unique Constraint)使用方法 1 目标 用演示样例演示怎样创建.删除.禁用和使用唯一性约束. 2 什么是唯一性约束? 唯一性约束指表中一个字段或 ...
- Odoo中如何复制有唯一性约束的记录?
转载请注明原文地址:https://www.cnblogs.com/cnodoo/p/9281393.html 如果为模型的字段添加了唯一性约束,那么在记录的form视图功能菜单上选择“复制”时就会 ...
随机推荐
- 分享我的“艺术品”:公共建筑能耗监测平台的GPRS通讯服务器的开发方法分享
在这个文章里面我将用一个实际的案例来分享如何来构建一个能够接受3000+个连接的GPRS通讯服务器软件,这个软件被我认为是一个艺术品,实现周期为1.5个月,文章很长,有兴趣的同志慢慢看.在这里,我将分 ...
- 深入理解openstack网络架构(1)
原文地址: https://blogs.oracle.com/ronen/entry/diving_into_openstack_network_architecture 译文转载自:http://b ...
- 开始VS 2012 中LightSwitch系列的第1部分:表中有什么?描述你的数据
[原文发表地址] Beginning LightSwitch in VS 2012 Part 1: What’s in a Table? Describing Your Data [原文发表时间] ...
- Web Essentials之Bundling
返回Web Essentials功能目录 本篇目录 介绍 样例文件 已知行为 介绍 这篇要讲的是Bundling,我看很多人把它翻译为捆绑,如果你喜欢你也可以这么理解,我是不太习惯,我还是喜欢它为bu ...
- 四则运算的实现(C++)重做
#include <iostream> using namespace std; void main() { int a0[1000],b0[1000],c0[1000],a1[1000] ...
- 作业七:团队项目——Alpha版本冲刺阶段-08
昨天进展:代码编写. 今天安排:代码编写.
- 走进AngularJs(八) ng的路由机制
在谈路由机制前有必要先提一下现在比较流行的单页面应用,就是所谓的single page APP.为了实现无刷新的视图切换,我们通常会用ajax请求从后台取数据,然后套上HTML模板渲染在页面上,然而a ...
- 十进制数转化成二进制后包含一的数量(c++)
#include <iostream> using namespace std;int func(int x){ int count=0; while(x){ ...
- 【原创】三分钟教你学会MVC框架——基于java web开发(2)
没想到我的上一篇博客有这么多人看,还有几位看完之后给我留言加油,不胜感激,备受鼓励,啥都别说了,继续系列文章之第二篇.(如果没看过我第一篇博客的朋友,可以到我的主页上先浏览完再看这篇文章,以免上下文对 ...
- 《30天自制操作系统》笔记(02)——导入C语言
<30天自制操作系统>笔记(02)——导入C语言 进度回顾 在上一篇,记录了计算机开机时加载IPL程序(initial program loader,一个nas汇编程序)的情况,包括IPL ...