(mit Entity Framework 6.2)Aktualisierung untergeordnete Objekte in Entity Framework 6
Ich habe die beiden folgenden Modelle/Einheiten:
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; }
}
und die folgenden DbContext
public DbSet<Country> Countries { get; set; }
Meine Frage ist, : Wenn sich die Kinder des Country-Objekts ändern (dh die Städte), wie aktualisiere ich das?
Kann ich dies tun:
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();
}
würde das funktionieren? Oder sollte ich spezifisch jede Stadt hinzufügen? d.h .:
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();' wird definitiv nicht funktionieren, da 'Countries' ein' DbSet 'ist, das keine' Cities' Eigenschaft hat;) –
Hehe, danke für die Antwort Balazs. Nicht sicher, ob einer von uns verwirrt ist, aber nicht die DbSet in der Tat eine Cities-Eigenschaft: ** öffentliche virtuelle ICollection Städte {Get; einstellen; } ** –
user1900799
Nein, nicht das 'DbSet', sondern eine tatsächliche Entität, dh eine' Country' ** - Instanz ** ist, was es enthält. –