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:

EntiLinq1.gif

EntiLinq2.gif

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:

EntiLinq3.gif

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:

EntiLinq4.gif

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.

EntiLinq5.gif

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

EntiLinq6.gif

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.

EntiLinq7.gif

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

EntiLinq8.gif

Up Next
    Ebook Download
    View all
    Learn
    View all