问题
I am able to validate an entity using the code entity.entityAspect.validateEntity()
. However, this does not validate navigation properties. My entiy has one-to-one and one-to-many relationship with out entities. I want to validate both the entity and its navigational properties. How can i do this with breeze?
EDIT I have a class
public class ClassA{
public int id{get; set;}
public List<ClassB> navigationArray{get; set;}
}
public class ClassB{
public int myClass {get; set;}
[Foreign("myClass")]
public ClassA ClassA_E{get; set;}
}
I add an object O1 of ClassA to the entity manager; and add an object O2 of classB to the entity manager and set the property, ClassA_E to O1. All works well but when validating O1, O2 does not get validated
回答1:
EntityAspect.validateEntity WILL validate navigation properties ( The code below was tested in breeze 1.4.17).
You can add your own validators to any navigation property: In the examples below assume a schema with "Customer" and "Order" entity types where each Customer has an nonscalar "orders" property and each "Order" has a scalar "customer" property.
In this case, the scalar "customer" navigation property on the Order type might have a validator registered like this:
var orderType = em.metadataStore.getEntityType("Order");
var custProp = orderType.getProperty("customer");
// validator that insures that you can only have customers located in 'Oakland'
var valFn = function (v) {
// v is a customer object
if (v == null) return true;
var city = v.getProperty("city");
return city === "Oakland";
};
var customerValidator = new Validator("customerValidator", valFn, { messageTemplate: "This customer's must be located in Oakland" });
custProp.validators.push(customerValidator);
where the validation error would be created by calling
myOrder.entityAspect.validateEntity();
And the nonscalar navigation property "orders" on the "Customer" type might have a validator registered like this:
var customerType = em.metadataStore.getEntityType("Customer");
var ordersProp = customerType.getProperty("orders");
// create a validator that insures that all orders on a customer have a freight cost > $100
var valFn = function (v) {
// v will be a list of orders
if (v.length == 0) return true; // ok if no orders
return v.every(function(order) {
var freight = order.getProperty("freight");
return freight > 100;
});
};
var ordersValidator = new Validator("ordersValidator", valFn, { messageTemplate: "All of the orders for this customer must have a freight cost > 100" });
ordersProp.validators.push(ordersValidator);
where the validation error would be created by calling
myCustomer.entityAspect.validateEntity();
来源:https://stackoverflow.com/questions/25576459/breeze-validate-entity-and-its-navigational-properties