using System;using System.ComponentModel.DataAnnotations;using System.Data.Entity;namespace Zwj.TEMS.Base{ ////// 唯一性标识 /// [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; } }}
在实体中使用方法如下:
////// 类别代码 /// [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(out attrs)) { bool result = attrs[0].IsValid(p.GetValue(entity, null)); Assert.IsTrue(result, "验证不唯一,存在重复值!"); } } }
public static class ClassExtension { ////// 尝试获取指定类别特性 /// ////// /// /// public static bool TryGetAttribute (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; } }