How to save an entity with a collection of related entities using WCF data services
-
30-05-2021 - |
Question
I have a new ParameterPart entity that is related to a new InputOutputMap. The InputOutputMap has several InputStates that I pull from the database and I need to associate with the InputOutputMap. How do I save this chain to the database using MVC and WCF Data services? I am using the following code (being called through an ajax call, context is only being set in the first call in the constructor) but am getting several issues:
- When I use AddLink (as shown below), I am able to add data the first time I try it (irrespective of how many inputstates I have to associate). If however, the method is called again (through ajax), I am only able to add data if I am specifying one inputstate. If I have multiple inputstates, I get context is already tracking the relationship. Note that the method is being called using an ajax call.
- I have tried using SetLink, AddRelatedObject and attach but everytime I am getting errors in the above scenario. Sometimes, the error is that context is already tracking the entity or the relationship. At other times, the context is not tracking the entity.
I didn't get any benefit when I set the context in the method instead of the constructor.
if (vm != null) { ParameterPart parameterPart = null; // Create a new parameter if (vm.PartNumberId == 0) { // Create an instance of ParameterPart parameterPart = new ParameterPart() { Description = vm.ParameterDescription }; // Save the ParameterPart into the database try { ctx.AddToParameterParts(parameterPart); ctx.SaveChanges(); } catch (System.Exception ex) { throw; } } else { // Fetch the existing parameter parameterPart = new ParameterPart(); parameterPart = (from pp in ctx.ParameterParts where pp.PartNumberId == vm.PartNumberId select pp).Single(); // Update the ParameterPart from the vm parameterPart.Description = vm.ParameterDescription; } if (parameterPart != null) { if (vm.StateValues.Count > 0) { InputOutputMap inputOutputMap = new InputOutputMap(); inputOutputMap.PartNumberId = parameterPart.PartNumberId; ctx.AddToInputOutputMaps(inputOutputMap); // Prepare a new InputOutputMap foreach (var state in vm.StateValues) { if (state.InputStateId != 0) { // Fetch the inputstate var inputState = (from i in ctx.InputStates where i.InputStateId == state.InputStateId select i).Single(); try { ctx.AddLink(inputOutputMap, "InputStates", inputState); ctx.SaveChanges(); } catch (System.Exception ex) { throw; } } } } } }
Solution
The AddLink method was working as desired. I was getting an error due to a data issue.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow