This is a migrated thread and some comments may be shown as answers.

Updating Parent Child entities with EF

0 Answers 154 Views
LINQ (LINQ specific questions)
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Vandana
Top achievements
Rank 1
Vandana asked on 16 Jul 2010, 05:07 AM

I have the following parent child relationship Employee > Employee Address with the relationship being 1 : n. I want to update the employee information as well as employee address at the same time. I am presently able to achieve this using the following code

System.Data.Objects.DataClasses.

 

EntityCollection<EmployeeAddress> address = new System.Data.Objects.DataClasses.EntityCollection<EmployeeAddress>();

 

address.Add(

 

 

new EmployeeAddress { Id = 10, EmployeeId = 33, Line1 = "Modified Line 1" });

 

emp =

 

 

new Employee() { Id = 33, Name = "ABC", Age = 50};

 

testDBContext.Employees.Attach(

 

 

new Employee { Id = emp.Id });

 

testDBContext.EmployeeAddresses.Attach(

 

 

new EmployeeAddress { Id = address.First().Id });

testDBContext.Employees.ApplyCurrentValues(emp);

testDBContext.EmployeeAddresses.ApplyCurrentValues(emp.EmployeeAddresses.First());

testDBContext.SaveChanges();

I have to perform two different operations to save the parent and child record. Is there any other efficient / better way to do this? I am presently in the EF learning phase. Any help on this will be highly appreciated. 

Thanks,

Vandana

Tags
LINQ (LINQ specific questions)
Asked by
Vandana
Top achievements
Rank 1
Share this question
or