Dot-Net

使用帶有 WPF 和實體框架的 DataAnnotations 驗證數據?

  • November 18, 2009

有什麼方法可以驗證在 WPF 和實體框架中使用 DataAnnotations 嗎?

您可以使用 DataAnnotations.Validator 類,如下所述:

<http://johan.driessen.se/archive/2009/11/18/testing-dataannotation-based-validation-in-asp.net-mvc.aspx>

但是,如果您對元數據使用“夥伴”類,則需要在驗證之前註冊該事實,如下所述:

<http://forums.silverlight.net/forums/p/149264/377212.aspx>

TypeDescriptor.AddProviderTransparent(
 new AssociatedMetadataTypeTypeDescriptionProvider(typeof(myEntity), 
   typeof(myEntityMetadataClass)), 
 typeof(myEntity));

List&lt;ValidationResult&gt; results = new List&lt;ValidationResult&gt;();
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&lt;T, U&gt;(this T obj, ref Dictionary&lt;string, string&gt; 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&lt;ValidationResult&gt;();
   Validator.TryValidateObject(obj, validationContext, validationResults, true);

   if (validationResults.Count &gt; 0 && errors == null)
       errors = new Dictionary&lt;string, string&gt;(validationResults.Count);

   foreach (var validationResult in validationResults)
   {
       errors.Add(validationResult.MemberNames.First(), validationResult.ErrorMessage);
   }

   if (validationResults.Count &gt; 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&lt;string, string&gt; errors)
   {
       return this.IsValid&lt;Employee, Metadata&gt;(ref errors);
       //If the Employee class didn't have a buddy class,
       //I'd just pass Employee twice:
       //return this.IsValid&lt;Employee, Employee&gt;(ref errors);
   }
}

引用自:https://stackoverflow.com/questions/1755340