2017-04-22 33 views
0

我想確保我的模型的列表屬性不爲空,所以我創建了一個ValidationAttribute,但值列表<長>總是返回null即使物業裝飾與NoEmpty是類型列表<長>。對象名單<long>總是返回null

爲什麼?以及如何正確地做到這一點?

public class NoEmptyAttribute: ValidationAttribute 
{ 
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     var list = value as List<long>; 

     var msg = $"{validationContext.MemberName} can not bt empty"; 

     if (list == null) return new ValidationResult(msg); 

     return list.Count == 0 ? new ValidationResult(msg) : ValidationResult.Success; 
    } 
} 

我更新了我的代碼,而現在它工作正常:

public class NoEmptyAttribute: ValidationAttribute 
{ 
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     var list = value as IEnumerable; 

     var msg = $"{validationContext.MemberName} can not be null"; 

     if (list == null) return new ValidationResult(msg); 

     return list.Cast<object>().Any() ? ValidationResult.Success : new ValidationResult(msg); 
    } 
} 

爲什麼價值,因爲名單<長>總是返回空的原因是該值類型的HashSet的<長>。

+0

是'value'等於'null'或類型不'名單'? –

+1

你可以發佈你調用方法的代碼嗎?另一種可能性是單步執行代碼,或者用'(列表)值'替換'值爲列表',以獲得準確的錯誤消息,以便它不被轉換。 –

+1

@StefanKert此代碼在驗證時被稱爲隱含=>沒有用戶生成的代碼將顯式調用它 –

回答

1

我寫了一個單元測試(根據您的NoEmptyAttribute的代碼),一切都按預期方式工作

[TestClass()] 
public class NoEmptyAttributeTests 
{ 
    [TestMethod] 
    public void GetValidationResult_ListLongWithElements_ReturnsNull() 
    { 
     object obj = new object(); 
     object value = new List<long> { 1, 2 }; 

     ValidationContext ctx = new ValidationContext(obj) { MemberName = "Foo" }; 
     var noempty = new NoEmptyAttribute(); 
     var result = noempty.GetValidationResult(value, ctx); 
     Assert.IsNull(result); 
    } 

    [TestMethod] 
    public void GetValidationResult_ListLongEmpty_ReturnsCannotBeEmpty() 
    { 
     object obj = new object(); 
     object value = new List<long>(); 

     ValidationContext ctx = new ValidationContext(obj) { MemberName = "Foo" }; 
     var noempty = new NoEmptyAttribute(); 
     var result = noempty.GetValidationResult(value, ctx); 
     Assert.IsNotNull(result); 
     Assert.AreEqual("Foo can not bt empty", result.ErrorMessage); 
    } 

    [TestMethod] 
    public void GetValidationResult_ListLongNull_ReturnsCannotBeEmpty() 
    { 
     object obj = new object(); 
     object value = null; 

     ValidationContext ctx = new ValidationContext(obj) { MemberName = "Foo" }; 
     var noempty = new NoEmptyAttribute(); 
     var result = noempty.GetValidationResult(value, ctx); 
     Assert.IsNotNull(result); 
     Assert.AreEqual("Foo can not bt empty", result.ErrorMessage); 
    } 
} 
+0

感謝您的回覆,我想出了它,並且我需要此屬性以適應不同類型。 –

+0

然後你應該考慮重命名爲'CollectionNotEmptyAttribute' –