TryValidateProperty不适用于泛型函数

时间:2012-01-06 07:01:00

标签: c# data-annotations validation

更新: 当我执行单元测试项目然后它将返回未处理此测试结果还包含内部异常而不是“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());
    }

以下是验证个人财产的通用功能

    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;
    }

以下是模型,其中描述字段标识为必需

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方法没有得到相同的错误?

请帮助我.....

1 个答案:

答案 0 :(得分: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);

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

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

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