2012-01-06 67 views
1

更新:当我执行 单元测试项目,然后将返回了未处理这个测试结果中还包含一个内部异常,而不是“Assert.IsTrue失败,需要说明字段“。结果像(0垭口,1次失败,1合计),但我们没有得到任何例外可言,如果我用F11TryValidateProperty无法与泛型函数工作

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

我得到错误的模型“的描述字段是必需的”如果我没有验证泛型方法,但为什么不是在得到相同错误使用通用方法?

请帮我.....

+2

“不工作”是一个非常羊毛的描述。请说出你预计会发生什么,以及发生了什么。 – 2012-01-06 07:03:59

+1

请将该信息编辑到问题中,而不是在评论中。 – 2012-01-06 07:13:24

+0

感谢您的意见,并根据您的意见更新我的问题。 – 2012-01-06 07:16:07

回答

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我自己),但它可以是答案。

+0

谢谢Jon Skeet ... – 2012-01-06 09:26:09