在 Entity Framework 6 中更新子对象

编程入门 行业动态 更新时间:2024-10-27 14:33:34
本文介绍了在 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 中更新子对象

本文发布于:2023-11-25 01:04:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1627685.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   Entity   Framework

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!