Consider the following situation. I have an Entity named ProductSupplier that is a Presentation Model. It is created by doing an inner join of Products and Suppliers, and creating a new projection from a Linq statement. The ProductSupplier projection also creates a list of PartType objects, which is also a Presentation Model.
public partial class ProductSupplier
{
private IEnumerable<PartType> _partTypes;
[Key]
public int ProductSupplierKey { get; set }
[Include]
[Association("ProductSupplier_PartType", "ProductSupplierKey", "ProductSupplierKey")]
public IEnumerable<PartType> PartTypes
{
get { return _partTypes ?? (_partTypes = new List<PartType>()); }
set { if (value != null) _partTypes = value; }
}
}
public partial class PartType
{
[Key]
public int PartTypeKey { get; set; }
[Key]
public int ProductSupplierKey { get; set; }
开发者_开发技巧 public int PartQuantity { get; set; }
}
I want to have a validation that is no ProductSupplier can be have more than 10 separate parts. This means that all PartQuantities for all PartTypes that belong to a ProductSupplier should be summed, and the total cannot exceed 10.
For this, I created a custom validator:
public static ValidationResult ValidatePartTotals(ProductSupplier productSupplier, ValidationContext validationContext)
{
if (productSupplier.PartTypes.Sum(p => p.PartQuantity) > 10)
return new ValidationResult("Must be less than 10 parts total.");
return ValidationResult.Success;
}
This works fine when validation is called from the client-side. The problem I'm having is that when the validator is run from the server-side, the IEnumerable is always empty.
I have tried adding [RoundTripOriginal] to the PartQuantity, and to various other properties, such as all the Key fields, but it still is an empty list when done on the server side.
How can I access these PartType objects when validation is run on the server?
Unfortunately, you don't have any guarantees as to the state of the object graph when it gets to you on the server. RIA optimizes things so you'll only see modified entities. One solution would be to use composition. It will make sure the whole graph is passed around, but it has other effects that may not be what you want. Another option would be to hydrate the graph in your update method, then perform validation, and throw a ValidationException as necessary.
精彩评论