自定义验证唯一属性-通用类 [英] Custom validation unique property - generic classes

查看:59
本文介绍了自定义验证唯一属性-通用类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试进行自定义验证[IsUnique].检查属性值是否唯一,并返回正确的消息.

I'm trying to make a custom validation [IsUnique]. That check if is property value is unique and return a proper message.

这是我的代码,但这仅适用于指定的类,是否可以执行一种通过元数据获取正确的类的方法?

This is my code, but this only work for a specified class, is possible to do a method that get the proper class by the metadata?

public class ArticleMetaData
    {
        [Required(AllowEmptyStrings = false)]
        [IsUnique("Name")]
        public String Name{ get; set; }      
    }

我的自定义验证:

class IsUnique : ValidationAttribute
    {
        public IsUnique(string propertyNames)
        {
            this.PropertyNames = propertyNames;
        }

        public string PropertyNames { get; private set; }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {

            var myproperty = validationContext.ObjectType.GetProperty(PropertyNames);
            var value = propiedad.GetValue(validationContext.ObjectInstance, null);

            IEnumerable<String> properties;

            List<string> propertiesList = new List<string>();
            propertiesList.Add(myproperty.Name);

            var dba = new myContext();

            if (dba.Articles.Any(article => article.Name == (string)value))
            {
                return new ValidationResult("The name already exist", propertiesList);
            }
            return null;
        }
    }

想法是只使用批注[isUnique],然后该方法将带有批注的类用于搜索相应的实体.

the idea would be to just use the annotation [isUnique] and the method take the class with annotation and search the corresponding entity.

推荐答案

在编写验证属性时,可以使用

When writing Validation Attributes, you can use ValidationContext to gain some information about validation such as Name of Property that you are validating, Type of object that you are validating and so on.

因此,您不需要声明要检查哪个属性的唯一性,也不需要声明要检查的实体,或者不需要使用反射来检索值的事件,因为该值已传递给IsValid方法.

So you don't need to declare which property you want to check for uniqueness, or which entity you should check, or event you don't need to retrieve value using reflection, because the value has been passed to IsValid method.

使用DbContext时,您可以执行Sql查询,因此您可以简单地使用sql查询来检查唯一性.比尝试动态创建通用linq查询要简单.

When using DbContext, you canexecute Sql queries, so you can check for uniqueness using sql query simply. It is more simple than try to Create generic linq query on the fly.

这个想法可能对您有帮助.根据您的想法,这是您的代码中的一些更改:

May be this idea help you. Here is some changes in your code according to the idea:

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    var db = new YourDBContext();

    var className = validationContext.ObjectType.Name.Split('.').Last();
    var propertyName = validationContext.MemberName;
    var parameterName = string.Format("@{0}", propertyName);

    var result = db.Database.SqlQuery<int>(
        string.Format("SELECT COUNT(*) FROM {0} WHERE {1}={2}", className, propertyName, parameterName),
        new System.Data.SqlClient.SqlParameter(parameterName, value));
    if (result.ToList()[0] > 0)
    {
        return new ValidationResult(string.Format("The '{0}' already exist", propertyName),
                    new List<string>() { propertyName });
    }

    return null;
}

要使用此属性,只需在属性上方放置[IsUnique].

To use this attribute, simply put [IsUnique] above your property.

[IsUnique]
YourProperty { get; set; }

然后使用以下代码运行测试:

Then run a test using such code:

var db = new YourDbContext();
db.Configuration.ValidateOnSaveEnabled = true;
db.Categories.Add(new YourEntity() { YourProperty = "DuplicateName" });
db.SaveChanges();

优良作法是仅使用可以离线验证的属性来验证实体的这一方面.

It is a good practice to validate only such aspect of your entity using attributes, that can be validated offline.

诸如StringLength,RegularExpression,Required之类的验证属性是良好属性的示例,而检查唯一性或其他与数据库相关的规则的验证属性是不适当属性的示例.

Validation Attributes like StringLength, RegularExpression, Required and such validations are examples of good attributes and Validation Attributes that checks for uniqness or other database related rules are examples of inappropriate attributes.

这篇关于自定义验证唯一属性-通用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆