(с помощью Entity Framework 6.2)Обновление дочерних объектов в Entity Framework 6
Я две следующие модели/лица:
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; }
}
И следующий DbContext
public DbSet<Country> Countries { get; set; }
Мой вопрос заключается в : Если меняются дети объекта Страны (например, Города), как мне это обновить?
Могу ли я сделать это:
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();
}
будет работать? Или я должен специально добавить каждый город? т.е .:
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();' определенно не будет работать, так как 'Страны'' 'DbSet', который не имеет свойства 'Cities';) –
Хехе, спасибо за ответ Balazs. Не уверен, что кто-то из нас сбит с толку, но у DbSet действительно есть свойство Cities: ** public virtual ICollection Города {get; задавать; } ** –
user1900799
Нет, это не 'DbSet', а фактический объект, то есть экземпляр' Country' **, который содержит его. –