MetadataType problem

后端 未结 3 491
别跟我提以往
别跟我提以往 2020-12-01 23:15

I\'m using VS2008 SP1, WCF Ria Service July 2009 CTP. I found out that MetadataType does not work in partial class mode, really don\'t know what I have missed out:

W

3条回答
  •  一生所求
    2020-12-01 23:32

    Many thanks to Jeremy Gruenwald for the answer above... I was completely stuck on this one.

    I wanted to create a standard validation class based on this solution, but I didn't want to have to pass in the metadata class type because it just felt ugly.

    To achieve this I created a static class which does a lookup on the custom attributes to get the metadata class type and then registers that class before returning the validation results.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    
    namespace MyApp.Validation
    {
        public static class EntityValidator
        {
            public static List Validate(object instance, bool validateAllProperties = true)
            {
                RegisterMetadataClass(instance);
    
                var validationContext = new ValidationContext(instance, null, null);
                var validationResults = new List();
    
                Validator.TryValidateObject(instance, validationContext, validationResults, validateAllProperties);
    
                return validationResults;
            }
    
            private static void RegisterMetadataClass(object instance)
            {
                var modelType = instance.GetType();
                var metadataType = GetMetadataType(modelType);
    
                if (metadataType != null) 
                {
                    TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(modelType, metadataType), modelType);
                }
            }
    
            private static Type GetMetadataType(Type type)
            {
                var attribute = (MetadataTypeAttribute)type.GetCustomAttributes(typeof (MetadataTypeAttribute), true).FirstOrDefault();
                return attribute == null ? null : attribute.MetadataClassType;
            }
        }
    }
    

    usage is a simple as:

    var errors = EntityValidator.Validate(myEntity);
    

提交回复
热议问题