gpt4 book ai didi

c# - Entity Framework 代码优先 : How to attach an entity and modify collection type property?

转载 作者:太空宇宙 更新时间:2023-11-03 13:21:59 25 4
gpt4 key购买 nike

我有一个实体“A”,它具有包含实体“B”集合的 ICollection 导航属性。

假设数据库包含对象“A1”,它的集合属性包含 3 个实体:“B1、B2、B3”。

现在我在代码中有分离实体“A1”,其集合属性包含分离实体“B3、B4”。

是否可以将对象“A1”附​​加到上下文并标记 Collection 属性也应该更新? (应删除实体B1、B2,应添加实体B4)

我尝试了以下方法,但它没有更新导航属性(集合)(仅更新标量属性):

context.Entry(A1).State = EntityState.Modified;

最佳答案

            using (var ctx = GetContext())
{
int[] ids = ctx.Bs.Select(x => x.Id).ToArray();
foreach (Bs b in A1.BsCollection)
{
if (!ids.Contains(b.Id))
ctx.Bs.Add(b);
else if(...){ ... }
}
ctx.As.Attach(A1);
ctx.Entry(A1).State = EntityState.Modified;
ctx.SaveChanges();
}

关于c# - Entity Framework 代码优先 : How to attach an entity and modify collection type property?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23813251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com