TryValidateProperty不适用于泛型函数

Man*_*lia 1 c# validation data-annotations

更新:当我执行单元测试项目然后它将返回未处理此测试结果还包含内部异常而不是 "Assert.IsTrue失败.描述字段是必需的." 结果如(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());
    }
Run Code Online (Sandbox Code Playgroud)

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

    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;
    }
Run Code Online (Sandbox Code Playgroud)

以下是Model,其中Description字段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; }
}
Run Code Online (Sandbox Code Playgroud)

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

请帮我.....

Jon*_*eet 7

比较这两个电话:

// 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);
Run Code Online (Sandbox Code Playgroud)

在第一种形式中,您传递了属性名称,即"描述".在第二种形式中,您传递了属性的,即"".要使第一个电话看起来像第二个,您需要:

typeof(T).GetProperty(PeropertyName).GetValue(t, null), 
Run Code Online (Sandbox Code Playgroud)

我不完全清楚这是你想要的(我没有用过Validator),但它可能就是答案.