DataAnnotations does not work with buddy class. The following code always validate true. Why ?
var isValid = Validator.TryValidateObject(new Customer(), Context, results, true);
and here is the buddy class.
public partial class Customer
{
public string Name { get; set; }
public int Age { get; set; }
}
[MetadataType(typeof(CustomerMetaData))]
public partial class Customer
{
public class CustomerMetaData
{
[Required(ErrorMessage = "You must supply a name for a customer.")]
public string Name { get; set; }
}
}
Here is another thread with same question., but no answer. link text
After some research I couldn't find any reason why TryValidateObject always return true if I use MetadataType (buddy class). But it works with the following code (xVal).
public static IEnumerable<ErrorInfo> GetErrors(object instance, string name)
{
var metadataAttrib = instance.GetType()
.GetCustomAttributes(typeof(MetadataTypeAttribute), true)
.OfType<MetadataTypeAttribute>().FirstOrDefault();
var buddyClassOrModelClass = metadataAttrib != null
? metadataAttrib.MetadataClassType
: instance.GetType();
var buddyClassProperties = TypeDescriptor.GetProperties(buddyClassOrModelClass)
.Cast<PropertyDescriptor>();
var modelClassProperties = TypeDescriptor.GetProperties(instance.GetType())
.Cast<PropertyDescriptor>();
var list = from buddyProp in buddyClassProperties
join modelProp in modelClassProperties on
buddyProp.Name equals modelProp.Name
from attribute in buddyProp.Attributes.OfType<ValidationAttribute>()
where !attribute.IsValid(modelProp.GetValue(instance))
select new ErrorInfo(
buddyProp.Name,
attribute.FormatErrorMessage(modelProp.Name),
instance);
if (name != null)
list = list.Where(x => x.PropertyName == name);
return list;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With