TryValidateProperty不适用于泛型函数

本文关键字:函数 泛型 适用于 不适用 TryValidateProperty | 更新日期: 2023-09-27 18:19:32

更新:当我执行单元测试项目时,它将返回未处理此测试结果还包含一个内部异常,而不是"Assert.IsTrue failed.The Description field is required."结果类似于(0 Pass,1 FAIL,1 Total),但如果我使用F11 进行调试,我们根本没有得到任何异常

    [TestMethod]
    [Asynchronous]
    [Description("Determines whether the selected or single property is valide using the validation context or validate single properties.")]
    public void ValidateSigleWithDataAnnotation()
    {
        LookupsServices lookupsservices = new LookupsServices();
        Lookups lookups = new Lookups() { Description = "", LookupReference = 2, DisplayOrder = 50};
        lookupsservices.Lookups.Add(lookups);
        //THIS IS NOT WORKING
        string message = ValidateProperties.ValidateSingle(lookups, "Description");
        Assert.IsTrue(message.Equals(""), message);
        //THIS IS WORKING
        var results = new List<ValidationResult>();
        Validator.TryValidateProperty(lookups.Description , new ValidationContext(lookups, null, null) { MemberName = "Description" }, results);
        Assert.IsTrue(results.Count == 0, results[0].ToString());
    }

以下是验证单个属性的通用函数

    public static string ValidateSingle<T>(T t, string PeropertyName) where T : class
    {
        string errorMessage = "";
        var ValidationMessages = new List<ValidationResult>();
        bool ValidationResult = Validator.TryValidateProperty(typeof(T).GetProperty(PeropertyName).Name,  new ValidationContext(t, null, null) { MemberName =  PeropertyName} , ValidationMessages);
        if (!ValidationResult) errorMessage += string.Format("'n{0}", ValidationMessages[0]);
        return errorMessage;
    }

以下是需要描述字段id的型号

public class Lookups
{
    public Lookups() { }
    [Key]
    public virtual int LookupReference { get; set; }
    [Required]
    public virtual string Description { get; set; }
    public virtual int? DisplayOrder { get; set; }
}

如果我在没有Generic方法的情况下进行验证,我会得到错误"描述字段是必需的",但为什么不使用Generic法得到相同的错误?

请帮帮我……

TryValidateProperty不适用于泛型函数

比较这两个调用:

// In the generic method
Validator.TryValidateProperty(
    typeof(T).GetProperty(PeropertyName).Name, 
    new ValidationContext(t, null, null) { MemberName =  PeropertyName},
    ValidationMessages);
// The working call
Validator.TryValidateProperty(
    lookups.Description,
    new ValidationContext(lookups, null, null) { MemberName = "Description" },
    results);

在第一种形式中,您传入属性的名称,即"Description"。在第二种形式中,您将传入属性的,即"。要使第一个电话看起来像第二个,您需要:

typeof(T).GetProperty(PeropertyName).GetValue(t, null), 

我不完全清楚这是否是你想要的(我自己没有使用过Validator),但它可能是答案。