Validate data using DataAnnotations with WPF & Entity Framework?

后端 未结 7 2279
甜味超标
甜味超标 2020-11-29 19:10

Is there any way to validate using DataAnnotations in WPF & Entity Framework?

7条回答
  •  感动是毒
    2020-11-29 20:06

    You can use the DataAnnotations.Validator class, as described here:

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

    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 results = new List();
    ValidationContext context = new ValidationContext(myEntity, null, null)
    bool valid = Validator.TryValidateObject(myEntity, context, results, true);
    

    [Added the following to respond to Shimmy's comment]

    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(this T obj, ref Dictionary 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();
        Validator.TryValidateObject(obj, validationContext, validationResults, true);
    
        if (validationResults.Count > 0 && errors == null)
            errors = new Dictionary(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 errors)
        {
            return this.IsValid(ref errors);
            //If the Employee class didn't have a buddy class,
            //I'd just pass Employee twice:
            //return this.IsValid(ref errors);
        }
    }
    

提交回复
热议问题