简体   繁体   中英

Updating child objects in Entity Framework 6

(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 (ie 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? ie:

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

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.

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