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

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

问题描述

我正在尝试进行自定义验证[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.

推荐答案

在编写验证属性时,可以使用 ValidationContext 以获得一些有关验证的信息,例如您正在验证的属性名称,您正在验证的对象类型等等。

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.

Validation属性(例如StringLength,RegularExpression,Required)和此类验证是良好属性的示例,而用于检查唯一性或其他与数据库相关的规则的Validation属性是不适当属性的示例。

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.

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

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