Inserting/Updating 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 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,
02 | using System.Collections.Generic; |
11 | static DataClasses1DataContext context; |
12 | static void Main( string [] args) |
15 | context = new DataClasses1DataContext(); |
16 | context.Log = Console.Out; |
17 | context.Persons.InsertOnSubmit( |
22 | HireDate = DateTime.Now, |
23 | OfficeAssignment = new OfficeAssignment |
25 | Location = "Jamshedpur" |
31 | context.SubmitChanges(); |
32 | Console.ReadKey( true ); |
41 | Person p = new Person { PersonID = 1, FirstName = "Dhananjay " ,LastName= "Kumar" }; |
44 | var result = from r in context.Persons select r; |
45 | foreach (var r in result) |
47 | Console.WriteLine(r.FirstName); |
49 | Console.ReadKey( true ); |
51 | var res1 = from r in context.OfficeAssignments select r; |
52 | foreach (var a in res1) |
54 | Console.WriteLine(a.Location+ a.Person.PersonID); |
57 | Console.ReadKey( true ); |
75 | static void SavePerson(Person p) |
80 | context.Persons.InsertOnSubmit(p); |
85 | context.Persons.Attach(p, GetOriginal(p.PersonID)); |
86 | context.SubmitChanges(); |
91 | static Person GetOriginal( int id) |
93 | DataClasses1DataContext db = new DataClasses1DataContext(); |
94 | return db.Persons.Single(r => r.PersonID == id); |
I hope this post was useful. Thanks for reading
Posted by
Dhananjay Kumar 
No comments :
Post a Comment