I\'m trying to create a UniqueAttribute
using the System.ComponentModel.DataAnnotations.ValidationAttribute
I want this to be generic as in I c
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 :)