I’m using the ADO.Net Entity Framework. To handle input validation I’m trying to use DataAnnotations, I looked around on StavkOverflow and Google, and everywhere I found almost the same example of using MetadataType. However, I’ve been trying for hours and I cannot get it to work.. For some reason, the CustomAttributes from the EmployeeMetaData class are not being applied to the respective field/properties on the Employee class. Does anyone have any idea why this might be happening? And yes, I’m sure the property types and names match perfectly.
Any help is appreciated, I’ve been stuck on this for hours.
Thanks in advance.
EntityExtentions.cs
[MetadataType(typeof(EmployeeMetaData))]
public partial class Employee:IDataErrorInfo
{
public string Error { get { return String.Empty; } }
public string this[string property]
{
get
{
return EntityHelper.ValidateProperty(this, property);
}
}
}
public class EmployeeMetaData
{
[Required(AllowEmptyStrings=false, ErrorMessage = "A name must be defined for the employee.")]
[StringLength(50, ErrorMessage = "The name must be less than 50 characters long.")]
public string Name { get; set; }
[Required(ErrorMessage = "A username must be defined for the employee.")]
[StringLength(20, MinimumLength = 3, ErrorMessage = "The username must be between 3-20 characters long.")]
public string Username { get; set; }
[Required(ErrorMessage = "A password must be defined for the employee.")]
[StringLength(20, MinimumLength = 3, ErrorMessage = "The password must be between 3-20 characters long.")]
public string Password { get; set; }
}
EntityHelper.cs
public static class EntityHelper
{
public static string ValidateProperty(object obj, string propertyName)
{
PropertyInfo property = obj.GetType().GetProperty(propertyName);
object value = property.GetValue(obj, null);
List<string> errors = (from v in property.GetCustomAttributes(true).OfType<ValidationAttribute>() where !v.IsValid(value) select v.ErrorMessage).ToList();
// I was trying to locate the source of the error
// when I print out the number of CustomAttributes on the property it only shows
// two, both of which were defined by the EF Model generator, and not the ones
// I defined in the EmployeeMetaData class
// (obj as Employee).Username = String.Join(", ", property.GetCustomAttributes(true));
return (errors.Count > 0) ? String.Join("\r\n", errors) : null;
}
}
I used this one (URLs points to helpful articles where I took some ideas):
The biggest disadvantages of this validator were:
Attribute for validating complex type / nested object: