Validate data using DataAnnotations with WPF & Entity Framework?

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

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

7条回答
  •  悲哀的现实
    2020-11-29 20:07

    I think that what is missing from Craigs answer is how to actually check if there are validation errors. This is DataAnnotation validation runner written by Steve Sanderson for those who want to run validation check in deferent layer then presentation (http://blog.codeville.net/category/xval/ , the code is in example project):

    public static IEnumerable GetErrors(object instance)
    {
        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();
    
        return 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(string.Empty), instance);
    }
    

    I'm not familiar with WPF (not sure if there is some out-of-the-box solution for you question), but maybe you can use it.

    Also, there are some comments on his blog that in some cases it fails to evaluate validation rule properly but it never failed for me.

提交回复
热议问题