Mou Mou - 29 days ago 5
C# Question

Entity Framework: How to update child data in foreach loop

see my code

using (var db = new TestDBContext())
{
var existingCustomer = db.Customer
.Include(a => a.Addresses.Select(x=> x.Contacts))
.FirstOrDefault(p => p.CustomerID == 5);

existingCustomer.FirstName = "Test Customer122";

foreach (var Custaddress in existingCustomer.Addresses.FirstOrDefault(a => a.AddressID == 5))
{
//Custaddress.
}
}


the foreach raising error


foreach statement cannot operate on variables of type
'EFTest.Addresses' because 'EFTest.Addresses' does not contain a
public definition for 'GetEnumerator'


i want to set child entity data in foreach loop and update in such a way as a result parent and child both will be updated. please drive me to right direction to get this job done.

Answer

That is because the method .FirstOrDefault returns an object of type source, not a list:

https://msdn.microsoft.com/en-us/library/bb340482(v=vs.110).aspx

Try:

    using (var db = new TestDBContext())
    {
        var existingCustomer = db.Customer
        .Include(a => a.Addresses.Select(x=> x.Contacts))
        .FirstOrDefault(p => p.CustomerID == 5);

        existingCustomer.FirstName = "Test Customer122";

        foreach (var custAddress in existingCustomer.Addresses.Where(a => a.AddressID == 5))
        {
            //do stuff
        }

        db.SaveChanges();
    }
Comments