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

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约束[转])