Updating child objects in Entity Framework 6

.net c# entity-framework entity-framework-6

Question

6.2 Entity Framework is used.

I have the two models or entities shown below:

public class City
    {
        public int CityId { get; set; }
        public string Name { get; set; }
    }

public class Country
    {
        public Country()
        {
            Cities new HashSet<City>();
        }

        public int CountryId { get; set; }
        public string Name { get; set; }
        public virtual ICollection<City> Cities { get; set; }
    }   

Aside from that DbContext

public DbSet<Country> Countries { get; set; }

How do I update this if the Cities, which are the Country object's children, change?

Is this possible?

List<City> cities = new List<City>();
// Add a couple of cities to the list...
Country country = dbContext.Countries.FirstOrDefault(c => c.CountryId == 123);
if (country != null)
{
    country.Cities.Clear();
    country.Cities = cities;
    dbContext.SaveChanges();
}

Is that possible? Or should I add each city separately? i.e.:

List<City> cities = new List<City>();
// Add a couple of cities to the list...
Country country = dbContext.Countries.FirstOrDefault(c => c.CountryId == 123);
if (country != null)
{
    country.Cities.Clear();
    foreach (City city in cities)
        country.Cities.Add(city);
    dbContext.SaveChanges();
}  
1
4
2/23/2017 9:53:35 AM

Accepted Answer

ZZZ_tmp
6
2/24/2017 10:53:55 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow