我有以下实体(这是 EF 生成的实体的一部分):
[MetadataType(typeof(ProjectItem_Metadata))]
public partial class ProjectItem : IIdentified, IValidatableObject
{
internal class ProjectItem_Metadata
{
[Editable(false)]
public int ID { get; set; }
public int ProjectID { get; set; }
public int? ReorderParentID { get; set; }
public int LibraryItemID { get; set; }
[Range(0, double.MaxValue, ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "QuantityError")]
public int Quantity { get; set; }
public float Width { get; set; }
public float Height { get; set; }
public float Depth { get; set; }
public int SheetMaterialID { get; set; }
public int? BandingMaterialID { get; set; }
public float MaterialVolume { get; set; }
public float MaterialWeight { get; set; }
public double EstimatedItemMass { get; set; }
public float SurfaceFootage { get; set; }
}
public static class Resources
{
private static readonly IStringProvider _errors = Strings.Current.GetGroup("ProjectItemErrors");
// Errors
public static string QuantityError { get { return _names.GetValueOrDefault("Quantity", "Quantity"); } }
}
public IEnumerable<ValidationResult> Validate(ValidationContext a_validationContext)
{
IStringProvider _errors = Strings.Current.GetGroup("ProjectItemErrors");
var libraryItem = LibraryItem;
if (libraryItem == null)
{
using (var context = new YouBuildEntities())
libraryItem = context.LibraryItems.SingleOrDefault(i => i.ID == LibraryItemID);
}
var validationResults = new List<ValidationResult>();
if (Width < libraryItem.MinWidth)
validationResults.Add(new ValidationResult(_errors.GetValue("WidthTooSmall", libraryItem.MinWidth), new String[] { "Width" }));
if (Width > libraryItem.MaxWidth)
validationResults.Add(new ValidationResult(_errors.GetValue("WidthTooLarge", libraryItem.MaxWidth), new String[] { "Width" }));
if (Height < libraryItem.MinHeight)
validationResults.Add(new ValidationResult(_errors.GetValue("HeightTooSmall", libraryItem.MinHeight), new String[] { "Height" }));
if (Height > libraryItem.MaxHeight)
validationResults.Add(new ValidationResult(_errors.GetValue("HeightTooLarge", libraryItem.MaxHeight), new String[] { "Height" }));
if (Depth < libraryItem.MinDepth)
validationResults.Add(new ValidationResult(_errors.GetValue("DepthTooSmall", libraryItem.MinDepth), new String[] { "Depth" }));
if (Depth > libraryItem.MaxDepth)
validationResults.Add(new ValidationResult(_errors.GetValue("DepthTooLarge", libraryItem.MaxDepth), new String[] { "Depth" }));
return validationResults;
}
}
当我这样调用 Validator.TryValidateObject 时:
var results = new List<ValidationResult>();
if (!Validator.TryValidateObject(_target, new ValidationContext(_target, null, null), results, true))
{
}
它验证Height
, Width
,Depth
但它忽略Quantity
. 我究竟做错了什么?
谢谢。