How can I create a generic UniqueValidationAttribute in C# and DataAnnotation?

后端 未结 4 656
感动是毒
感动是毒 2021-02-03 15:44

I\'m trying to create a UniqueAttribute using the System.ComponentModel.DataAnnotations.ValidationAttribute

I want this to be generic as in I c

4条回答
  •  孤街浪徒
    2021-02-03 16:06

    as @LBushkin mentioned, Attributes need compile time constants.

    I would change your class from:

    public class UniqueAttribute : ValidationAttribute
    

    to:

    public class UniqueAttribute : ValidationAttribute  
    where T : DataContext{
    
        protected T Context { get; private set; }
    
      ...    
    
        }
    

    and use it as:

    [Required]
    [StringLength(10)]
    [Unique("Groups","name")]
    public string name { get; set; }
    

    This will help you inject a DataContext object, if needed, instead of creating an instance everytime

    HTH

    Edit: since an attribute cannot take a generic parameter, this could be another potential code:

    public class UniqueAttribute : ValidationAttribute{
    
        public UniqueAttribute(Type dataContext, ...){
            if(dataContext.IsSubClassOf(typeof(DataContext))){
                var objDataContext = Activator.CreateInstance(dataContext);
            }
        }
    
    }
    

    and use it as:

    [Required]
    [StringLength(10)]
    [Unique(typeof(DataContext), "Groups","name")]
    public string name { get; set; }
    

    HTH this time :)

提交回复
热议问题