Updating child objects in Entity Framework 6(在 Entity Framework 6 中更新子对象)
问题描述
(使用实体框架 6.2)
(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; }
}
还有下面的DbContext
And the following DbContext
public DbSet<Country> Countries { get; set; }
我的问题是:如果 Country 对象的子对象发生变化(即 Cities),我该如何更新?
My question is: If the children of the Country object change (i.e. the Cities), how do I update 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();
}
推荐答案
您需要将 Cities
添加到正在更新的特定 Country
对象.
You need to add Cities
to that particular Country
object which is being updated.
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;}
}
希望对你有帮助.
这篇关于在 Entity Framework 6 中更新子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Entity Framework 6 中更新子对象
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01