I have an object in SQL (A) that has a many to many relationships with another object (B). I’m currently building an API layer DLL that will allow the user to assign objects of type B into type A. Right now the user would retrieve a list of entries of type A and a list of entries of type B using different LINQ data contexts. The problem is it the data context associated with A treats any objects from the data context associated with B as if they were new and tries to insert them when I call SubmitChanges(). Is there a way to tell data context A that these objects already exist and don’t need to be created? The code I’d like to write looks something like this (I’ll call A service and B output):
List<Service> svcs = Service.GetServices(); List<Output> outs = Output.GetOutputs(); svcs[0].OutputCollection.Add(outs); svcs[0].Save();
Each Service object in my example has a reference to the data context that pulled it from the database and the Save function calls DataContext.SubmitChanges(); The code above throws an exception because it tries to add the Output that already exists back to the table.
I know this was long and I’m not sure I explained my problem well. Any insight or suggestions would be helpful.
I actually found a different sort of solution and now i feel kind of stupid for even asking the question. What I did inside the Service.Outputs.Add() method was really the problem:
What I should have done is: