简体   繁体   中英

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.

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM