随笔 - 163  文章 - 2  评论 - 370  阅读 - 46万 
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;
        }
    }
posted on   风浪  阅读(614)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示