(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();
}
dbContext.Countries.Cities.Clear();will definitely not work sinceCountriesis aDbSet<Country>which does not have aCitiesproperty ;)DbSetbut an actual entity, that is, aCountryinstance is what contains it.