[英]Updating child objects in Entity Framework 6
(Using Entity Framework 6.2) (使用实体框架 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以及以下 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?我的问题是:如果 Country 对象的子项发生变化(即 Cities),我该如何更新?
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: 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.您需要将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;
}
}
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.希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.