DataAnnotations does not work with buddy class. The following code always validate true. Why ?
var isValid = Validator.TryValidateObject(new Customer(), Context, res
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 GetErrors(object instance, string name)
{
var metadataAttrib = instance.GetType()
.GetCustomAttributes(typeof(MetadataTypeAttribute), true)
.OfType().FirstOrDefault();
var buddyClassOrModelClass = metadataAttrib != null
? metadataAttrib.MetadataClassType
: instance.GetType();
var buddyClassProperties = TypeDescriptor.GetProperties(buddyClassOrModelClass)
.Cast();
var modelClassProperties = TypeDescriptor.GetProperties(instance.GetType())
.Cast();
var list = from buddyProp in buddyClassProperties
join modelProp in modelClassProperties on
buddyProp.Name equals modelProp.Name
from attribute in buddyProp.Attributes.OfType()
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;
}