Databases Reference
In-Depth Information
var context = new ValidationContext(entity, null, items );
var results = new List<ValidationResult>();
if (!Validator.TryValidateObject(entity, context, results, true))
{
ThrowValidationException(entity, results);
}
}
Notice the ObjectStateEntry instance is stored in the dictionary using its own type as the
key. This is not a strict requirement; you simply need a well-known value to serve as the
key so that validation methods can find it in the dictionary. Using the type itself simply
avoids having to define an extra constant just for this purpose. The dictionary is passed to
the ValidationContext constructor as the third parameter.
Having changed the validation infrastructure to store the ObjectStateEntry instances in
the ValidationContext , you can now implement a validation method in the Order class
that takes advantage of it:
[MetadataType(typeof(Order.Metadata))]
partial class Order
{
private abstract class Metadata
{
[CustomValidation(typeof(Order), “ValidateOrderStatus”)]
public object OrderStatus { get; set; }
}
public static ValidationResult ValidateOrderStatus(
byte? newStatus, ValidationContext context)
{
var stateEntry = (ObjectStateEntry)
context.Items[typeof(ObjectStateEntry)];
if (stateEntry.State == EntityState.Modified)
{
byte? oldStatus = (byte?)stateEntry.OriginalValues[“OrderStatus”];
if (oldStatus == (byte?)DataModel.OrderStatus.Fulfilled &&
newStatus != (byte?)DataModel.OrderStatus.Fulfilled)
{
return new ValidationResult(
“Status of fulfilled orders should not be modified”,
new string[] { “OrderStatus” });
}
}
return ValidationResult.Success;
}
Search WWH ::




Custom Search