1

Everywhere I look about validating the response before saving to the DB, in breeze, they are overriding the BeforeSaveEntity or BeforeSaveValidation. e.g. breezejs issues with the save bundle. Is there anyway we can validate the savebundle before calling the saveChanges(), like in the repository level?

I want to pass the JObject savebundle from the controller to the relevant repository and do a few things there: 1) Check if the user has permission to save this entity 2) Do business-logic level validation 3) Do entity level operations such as updating the changedDate and changedUser, add default values to some other entity etc...

These are more like business-logic level operations and in our application we have like 20+ such entities that get saved from different parts of the application. If we override BeforeSaveEntity() we are doing all such business logic level validations for all entities inside the DataContext. Like

`if (entityInfo.Entity.GetType() == typeof(MyEntityTypeModel)) {
 }`

I don't think if-else or case condition for 20+ entities is a good design. Besides, we have a clear separation of concerns through the use of repositories, so I think that's where this should be done.

How do we manipulate/validate the savebundle in such case?

Community
  • 1
  • 1
devC
  • 1,384
  • 5
  • 32
  • 56

1 Answers1

0

Use the BeforeSaveEntities method ( documented here: http://www.getbreezenow.com/breeze-sharp-documentation/contextprovider). With this method you can work with ALL of the entities of a specified type without having to perform an 'if' test on each one.

Code might look something like this:

ContextProvider.BeforeSaveEntitiesDelegate = CheckFreightOnOrders;
return ContextProvider.SaveChanges(saveBundle);

private Dictionary<Type, List<EntityInfo>> CheckFreightOnOrders(Dictionary<Type, List<EntityInfo>> saveMap) {
  List<EntityInfo> entityInfos;
  // extract just those entities of type 'Order'
  if (saveMap.TryGetValue(typeof(Order), out orderEntityInfos)) {
    // then iterate over them.
    foreach (var entityInfo in orderEntityInfos) {
      CheckFreight(entityInfo);
    }
  }

  return saveMap;
}
Jay Traband
  • 17,053
  • 1
  • 23
  • 44
  • What if I want to set some properties to the entity? Or add another type of an entity? Say for example, I have a Course entity, when I add a new Course, I have to add some default classes to the CourseClasses entity. Can I simply add it to the savemap? – devC Jan 30 '15 at 18:00
  • Yep, just modify the existing saveMap by adding, removing or changing the entities within it. – Jay Traband Jan 30 '15 at 18:20
  • Even here, if I want to modify another entity type - say student, I have to use else if (saveMap.TryGetValue(typeof(Student), out studentEntityInfo) etc... right? I'm trying to avoid that – devC Jan 30 '15 at 18:25