Updating child objects in Entity Framework 6

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

Question

(Using Entity Framework 6.2)

I have the following two models/entities:

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

And the following DbContext

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

My question is: If the children of the Country object change (i.e. the Cities), how do I update this?

Can I do this:

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

Would that work? Or should I specifically add each city? 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

You need to add Cities to that particular Country object which is being updated.

public Country Update(Country country)
{
    using (var dbContext =new DbContext())
    {
        var countryToUpdate = dbContext.Countries.SingleOrDefault(c => c.Id == country.Id);
        countryToUpdate.Cities.Clear();
        foreach (var city in country.Cities)
        {
            var existingCity =
                dbContext.Cities.SingleOrDefault(
                    t => t.Id.Equals(city.cityId)) ??
                dbContext.Cities.Add(new City
                {
                    Id = city.Id,
                    Name=city.Name
                });

            countryToUpdate.Cities.Add(existingCity);
        }
        dbContext.SaveChanges();
        return countryToUpdate;
    }
}

Update :

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

        [ForeignKey("Country")]
        public int CountryId {get;set;}
        public virtual Country Country {get; set;}
    } 

Hope it helps.

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