Inserting Record on Related Entities Using LINQ

It is a very common scenario that you need to insert rows in related tables using LINQ. Assume you have two tables as below:



Insert a Person with no Office Assignment

If you have a requirement to insert a Person without any Office Assignment then that it is simple to do as shown below:


If you need to insert an Office Assignment while inserting a Person, you can create an instance of an office assignment and insert that as well with the Person as shown below:


Now I have created a function to perform both an insert and an update. If you provide a person Id of 0 then this function will insert a new row else it will update the existing row.


When I tried to call the above function to update Person with ID 1, I encountered the following exception:


To get rid of that exception, you need to call attach with the original entity as well. We need to pass a modified entity as well as an original entity to make a call.


And while attaching you need to call the above function as below: