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;
}
}
以下是博客園的相關文章,他主要描述的是如何在數據庫中生成唯 一性索引,而對如何在C#進行唯一性驗證並沒有說明,我這篇文章僅作一個補充。