Mou Mou - 1 month ago 6
C# Question

Entity Framework: How to include nested child during add or update data to db

this below way i am inserting customer and nested child. customer has child called address and address has child called contacts details.

using (var db = new TestDBContext())
{
var customer = new Customer
{
FirstName = "Test Customer1",
LastName = "Test Customer1",
Addresses = new List<Addresses>
{
new Addresses
{
Address1 = "test add1",
Address2 = "test add2",
IsDefault=true,
Contacts = new List<Contacts>
{
new Contacts { Phone = "1111111", Fax = "1-1111111",IsDefault=true, SerialNo=1 },
new Contacts { Phone = "2222222", Fax = "1-2222222",IsDefault=false, SerialNo=2 }
}
},
new Addresses
{
Address1 = "test add3",
Address2 = "test add3",
IsDefault=false,
Contacts = new List<Contacts>
{
new Contacts { Phone = "33333333", Fax = "1-33333333",IsDefault=false, SerialNo=1 },
new Contacts { Phone = "33333333", Fax = "1-33333333",IsDefault=true, SerialNo=2 }
}
}

}
};

db.Customer.Add(customer);
db.SaveChanges();

int id = customer.CustomerID;
}


suppose now i want to update customer and its associated address and contacts details.

i browser few similar thread here. i saw people deleting child data and insert new one instead of update. here is one link http://stackoverflow.com/a/27177623/728750

they include child this way

var existingParent = _dbContext.Parents
.Where(p => p.Id == model.Id)
.Include(p => p.Children)
.SingleOrDefault();


but in my case i have multiple child say like address and contact details then how could i Include first address of customer and then i like to include contact details child of address.

please tell me how to do it.

Answer

Are you looking for this

using System.Data.Entity; // NB!

var company = dbContext.Parents
                     .Include(co => co.Addresses.Select(ad=> ad.Contacts))
                     .FirstOrDefault(p =>  p.Id == model.Id);