This question stems off of this other article. I'm currently using BreezeJS with Entity Framework but I don't believe I am using it quite the way it was intended. Currently I am calling save changes on an array of entities that I am sending to the server and then deserializing them into their original structure. I'm hoping there's a better way to do this that I just haven't been able to find. There are two ways I see I could do this but can't get them to work.
First would be to send the array over as a single object that when deserialized would already be in the object structure. When client side that is the format the object is held in so it wouldn't take any additional work.
The second option would be to somehow use the array that is sent to the server and build the object structure using the Entity Framework Metadata within EFContextProvider.
If possible I would prefer a solution closer to option one.
Javascript
function saveObjects() {
// Assume the child class has a foreign key to the parent
var parent = dataService.createEntity('PARENT', parentObject);
var child = dataService.createEntity('CHILD', childObject);
// Save changes
// This is what I'm currently doing because each entity is seperate
dataService.saveChanges([parent, child]);
// This is what I would like to do
// dataService.saveChanges(parent);
}
The object that is currently sent looks like this. I want CHILD to actually be a child within the PARENT object when it gets sent across.
// Current saveBundle
{"entities": [
{"ID: 1,
"entityAspect": {"entityTypeName": "PARENT", ...}},
{"PARENT_ID: 1,
"entityAspect": {"entityTypeName": "CHILD", ...}}
]}
// Ideal saveBundle
{"entities": [
{"ID: 1,
{"PARENT_ID: 1,
"entityAspect": {"entityTypeName": "CHILD", ...}},
"entityAspect": {"entityTypeName": "PARENT", ...}},
]}
C#
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
// Currently I have to deserialize each object and rebuild the object
// because the save bundle is a list of single entities instead of
// the existing object hierarchy
PARENT parent = DeserializeEntity(saveBundle, 'PARENT');
parent.child = DeserializeEntity(saveBundle, 'CHILD');
// Custom Validation and Saving is done here
}
I may be using BreezeJS incorrectly but the validation and database saving happens in separate modules further down the line. I'm just trying to cut out some the manual work in the middle (having to rebuild the object structure).
One way to address your problem is to perform work in the
BeforeSaveEntities
method. There, the entities have already been deserialized, but are still not in an object graph. You can have EF arrange them in an object graph for you by attaching them to a separate Context (not the same one used for saving).See this SO question and answer for more details.