在Entity Framework 6中更新子对象

(使用Entity Framework 6.2)

我有以下两个模型/实体:

public class City { public int CityId { get; set; } public string Name { get; set; } } public class Country { public Country() { Cities new HashSet(); } public int CountryId { get; set; } public string Name { get; set; } public virtual ICollection Cities { get; set; } } 

以及下面的DbContext

 public DbSet Countries { get; set; } 

我的问题是:如果Country对象的子项发生变化(即城市),我该如何更新?

我可以这样做:

 List cities = new List(); // 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 cities = new List(); // 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(); } 

您需要将Cities添加到正在更新的特定Country对象。

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

更新:

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

希望能帮助到你。