使用带有 WPF & 的 DataAnnotations 验证数据实体框架? [英] Validate data using DataAnnotations with WPF & Entity Framework?
问题描述
有什么方法可以在 WPF & 中使用 DataAnnotations 进行验证?实体框架?
Is there any way to validate using DataAnnotations in WPF & Entity Framework?
推荐答案
您可以使用 DataAnnotations.Validator 类,如下所述:
You can use the DataAnnotations.Validator class, as described here:
但如果您对元数据使用伙伴"类,则需要在验证之前注册该事实,如下所述:
But if you're using a "buddy" class for the metadata, you need to register that fact before you validate, as described here:
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 的评论]
我写了一个通用方法来实现上面的逻辑,这样任何对象都可以调用它:
I wrote a generic method to implement the logic above, so that any object can call it:
// 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;
}
在每个需要验证的对象中,我添加了对这个方法的调用:
In each object that needs to be validated, I add a call to this method:
[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);
}
}
这篇关于使用带有 WPF & 的 DataAnnotations 验证数据实体框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!