Inserting/Updating Record on related entities using LINQIt 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 requirement to insert a Person without any Office Assignment then it is quiet straight forward task like below
If you need to insert Office Assignment while inserting Person, you can create instance of office assignment and insert along with Person like below,
Now I have created function to perform both Insert and update operation. If you provide person Id as 0 this function will insert a new row else it will update existing row.
When I tried to call above function to update Person with ID 1, I encountered with below exception
To get rid of above exception, you need to call attach with original entity as well. We need to pass modified entity as well as original entity to make a call.
So I created a function as below,
And while attaching you need to call above function as below
Full source code is as below,
Posted by Dhananjay Kumar