在WPF和Entity Framework中,有没有使用DataAnnotations进行验证的方法?
在WPF和Entity Framework中,有没有使用DataAnnotations进行验证的方法?
但是如果您在元数据中使用“buddy”类,则需要在验证之前注册该事实,如此处所述:
http://forums.silverlight.net/forums/p/149264/377212.aspx
TypeDescriptor.AddProviderTransparent(
new AssociatedMetadataTypeTypeDescriptionProvider(typeof(myEntity),
typeof(myEntityMetadataClass)),
typeof(myEntity));
List<ValidationResult> results = new List<ValidationResult>();
ValidationContext context = new ValidationContext(myEntity, null, null)
bool valid = Validator.TryValidateObject(myEntity, context, results, true);
[针对Shimmy的评论,添加以下内容]
我编写了一个通用的方法来实现上述逻辑,以便任何对象都可以调用它:
// If the class to be validated does not have a separate metadata class, pass
// the same type for both typeparams.
public static bool IsValid<T, U>(this T obj, ref Dictionary<string, string> errors)
{
//If metadata class type has been passed in that's different from the class to be validated, register the association
if (typeof(T) != typeof(U))
{
TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(T), typeof(U)), typeof(T));
}
var validationContext = new ValidationContext(obj, null, null);
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(obj, validationContext, validationResults, true);
if (validationResults.Count > 0 && errors == null)
errors = new Dictionary<string, string>(validationResults.Count);
foreach (var validationResult in validationResults)
{
errors.Add(validationResult.MemberNames.First(), validationResult.ErrorMessage);
}
if (validationResults.Count > 0)
return false;
else
return true;
}
在需要进行验证的每个对象中,我都会添加对此方法的调用:
[MetadataType(typeof(Employee.Metadata))]
public partial class Employee
{
private sealed class Metadata
{
[DisplayName("Email")]
[Email(ErrorMessage = "Please enter a valid email address.")]
public string EmailAddress { get; set; }
}
public bool IsValid(ref Dictionary<string, string> errors)
{
return this.IsValid<Employee, Metadata>(ref errors);
//If the Employee class didn't have a buddy class,
//I'd just pass Employee twice:
//return this.IsValid<Employee, Employee>(ref errors);
}
}
我认为克雷格的答案中缺少的是如何检查是否存在验证错误的方法。以下是由Steve Sanderson编写的DataAnnotation验证运行程序,适用于希望在演示层以外的不同层运行验证检查的人(http://blog.codeville.net/category/xval/,代码在示例项目中):
public static IEnumerable<ErrorInfo> GetErrors(object instance)
{
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>();
return 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(string.Empty), instance);
}
我不熟悉WPF(不确定是否有适合你问题的开箱即用解决方案),但或许你可以使用它。
此外,他的博客中有一些评论称在某些情况下会出现验证规则无法正确评估的问题,但这种情况从未在我的环境中出现过。
您可能会对 BookLibrary 示例应用程序感兴趣,它属于 WPF 应用程序框架 (WAF)。它正好符合您的要求:在 WPF 和 Entity Framework 中使用 DataAnnotations。
我编写了一个基于贡献者的验证器,其中包括一个DataAnnotation验证贡献者,并检查损坏的绑定(用户输入了不正确的类型)
http://adammills.wordpress.com/2010/07/21/mvvm-validation-and-type-checking/