我有一个带有 Entity Framework 对象的模型。 EF 对象实现 IValidatableObject
并具有 Validate() 方法。
由于某种原因,该方法运行了两次,因此我的页面上出现了两个相同的模型错误。
知道为什么会发生这种情况或如何阻止它吗?
我尝试添加一个 _isValidated
私有(private)成员变量,但它似乎每次运行时都会重置为 false,因此它必须创建并验证模型的两个实例。
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrWhiteSpace(CatName))
{
yield return new ValidationResult("Bad kitty", new string[] { "CatName", "CatName" });
}
}
编辑:我的模型:
public class KittyModel
{
public Cat Cat { get; set; }
public int? SomeId { get; set; }
public string SomeString { get; set; }
}
那么Cat
只是一个EF对象
[MetadataType(typeof(CatMetadata))]
public partial class Cat : IValidatableObject
{
public sealed class CatMetadata
{
[Required]
public int? CatTypeID { get; set; }
}
// Some other get; only properties here
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrWhiteSpace(CatName))
{
yield return new ValidationResult("Bad kitty", new string[] { "CatName", "CatName" });
}
}
}
最佳答案
我今天遇到了同样的问题...我相信这就是验证方法被调用两次的原因,from here :
If your model is a complex model inside of a complex model, validation might be called twice for model-level validators (which IValidatableObject is considered to be). That's because it's validated once as a stand-alone object, and then again as the property of its containing object.
关于c# - IValidatableObject Validate 方法运行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32091275/