Reader Level:

Inserting Record on Related Entities Using LINQ

By Dhananjay Kumar on Jun 27, 2011
Here you will see how to insert records for related entities using LINQ
  • 0
  • 0
  • 9612

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:


Dhananjay Kumar

Dhananjay kumar is an independent trainer, a consultant and a programmer from India. He has mentored more than 1000 professionals and known for his unique way of teaching. He has been part of the multiple projects for bi... Read more

Personal Blog: