简体   繁体   English

将数据注释添加到通过DLL引用提供的类中,该引用由多个应用程序共享

[英]Adding data annotations to a class provided through a DLL reference, that is shared by multiple applications

In my application I am using a class that is supplied by external library, and used across multiple applications. 在我的应用程序中,我使用的是外部库提供的类,该类可在多个应用程序中使用。 I would like to add Data Annotations to the properties of this class, but it must be contained within my application. 我想将数据注释添加到此类的属性中,但是它必须包含在我的应用程序中。

I've produced the following code that will retrieve all attributes for a property, but cannot find a way to add a Data Annotation attribute. 我已经生成了以下代码,该代码将检索属性的所有属性,但是找不到添加数据注释属性的方法。 Lets say I have a class called vehicle that has a property of VIN: 可以说我有一个叫做Vehicle的类,它具有VIN的属性:

AttributeCollection oldAttributeCollection = TypeDescriptor.GetProperties(instance).Find("VIN", true).Attributes;

The short answer is you can't add attributes to a class dynamically. 简短的答案是您不能动态地向类添加属性。 For more info see this related question 有关更多信息,请参见此相关问题

I found the solution. 我找到了解决方案。 The method below will execute for each property in the current model. 下面的方法将对当前模型中的每个属性执行。 I am able to apply some logic and determine if I want to add my custom "ConditionallyRequired" Data Annotation to the property. 我能够应用一些逻辑,并确定是否要将自定义的“ ConditionallyRequired”数据注释添加到属性。

  public class CustomMetadataValidationProvider : DataAnnotationsModelValidatorProvider
    {
        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
        {
            var validators = PermissionManager.Settings.Validation.ToList();
            var validateField =
                validators.SingleOrDefault(v => v.FieldName == metadata.PropertyName && v.IsValidated == "True");

            var attr = new List<Attribute>();
            attr.AddRange(attributes);
            if (validateField != null)
            {

                attr.Add(new ConditionallyRequired(validateField.FieldName));
            }
            return base.GetValidators(metadata, context, attr);
        }
    }

Then initialize the CustomMetadataValidationProvider class in the global.asax like so: 然后像下面这样在global.asax中初始化CustomMetadataValidationProvider类:

protected void Application_Start()
    {
        ModelValidatorProviders.Providers.Add(new ConditionallyRequired.CustomMetadataValidationProvider());
        AreaRegistration.RegisterAllAreas();

    }

右键单击您的类库,然后选择“管理NuGet程序包...”,然后在“浏览”选项卡->中:System.ComponentModel.DataAnnotations并安装

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM