C# MVC.net core:Validator.TryValidateObject未验证buddy类中定义的属性

C# MVC.net core:Validator.TryValidateObject未验证buddy类中定义的属性,c#,validation,data-annotations,asp.net-core-3.1,buddy-class,C#,Validation,Data Annotations,Asp.net Core 3.1,Buddy Class,我们使用DB-first方法在.NET核心应用程序中生成模型。DataAnnotation被放在“buddy”元数据类中,以避免写入自动生成的文件。当控制器调用TryValidateModel时,一切正常,需要Name属性 public partial class User { public string Name { get; set; } } [ModelMetadataType(typeof(UserMetaData))] public partial class User :

我们使用DB-first方法在.NET核心应用程序中生成模型。DataAnnotation被放在“buddy”元数据类中,以避免写入自动生成的文件。当控制器调用TryValidateModel时,一切正常,需要Name属性

public partial class User
{
    public string Name { get; set; }
}

[ModelMetadataType(typeof(UserMetaData))]
public partial class User : IValidatableObject
{
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { }
}

public class UserMetaData
{
    [Required]
    public string Name { get; set; }
}
公共部分类用户
{
公共字符串名称{get;set;}
}
[ModelMetadataType(typeof(UserMetaData))]
公共部分类用户:IValidatableObject
{
公共IEnumerable验证(ValidationContext ValidationContext){}
}
公共类用户元数据
{
[必需]
公共字符串名称{get;set;}
}
在应用程序的服务层上,我们希望实现额外的验证,该验证还检查对象对于数据注释是否有效。这是通过
Validator.TryValidateObject()
它成功地调用了Validate方法,但忽略了数据注释-用户是有效的,即使名称为空

TL;博士: MVC(Web Project)知道如何通过MODEM Meta ADATATYPE属性考虑在“好友”类中放置的数据注释,服务层项目不这样做。 我以为我找到了答案,但似乎
TypeDescriptor.AddProviderTransparent
不适用于.net核心应用程序


如果您有任何想法,我们将不胜感激。

我真的希望有一个单线解决方案:)

我这样回答他自己的问题:

var metadataAttr = typeof(T).GetCustomAttributes(typeof(ModelMetadataTypeAttribute), true).OfType<ModelMetadataTypeAttribute>().FirstOrDefault();
if (metadataAttr != null)
{
    var metadataClassProperties = TypeDescriptor.GetProperties(metadataAttr.MetadataType).Cast<PropertyDescriptor>();
    var modelClassProperties = TypeDescriptor.GetProperties(typeof(T)).Cast<PropertyDescriptor>();

    var errs =
        from metaProp in metadataClassProperties
        join modelProp in modelClassProperties
        on metaProp.Name equals modelProp.Name

        from attribute in metaProp.Attributes.OfType<ValidationAttribute>()
        where !attribute.IsValid(modelProp.GetValue(model))
        select new ValidationResult(attribute.FormatErrorMessage(Reflector.GetPropertyDisplayName<T>(metaProp.Name)), new[] { metaProp.Name });

    validationResults.AddRange(errs);
}
var metadataAttr=typeof(T).GetCustomAttributes(typeof(ModelMetadataTypeAttribute),true).OfType().FirstOrDefault(); 如果(metadataAttr!=null) { var metadataClassProperties=TypeDescriptor.GetProperties(metadataAttr.MetadataType).Cast(); var modelClassProperties=TypeDescriptor.GetProperties(typeof(T)).Cast(); var错误= 从metadataClassProperties中的metaProp 在modelClassProperties中加入modelProp 在metaProp.Name上等于modelProp.Name 来自metaProp.Attributes.OfType()中的属性 其中!attribute.IsValid(modelProp.GetValue(model)) 选择new ValidationResult(attribute.FormatErrorMessage(Reflector.GetPropertyDisplayName(metaProp.Name)),new[]{metaProp.Name}); validationResults.AddRange(错误); }