【发布时间】:2020-04-28 08:09:10
【问题描述】:
尝试对具有嵌套列表的实体执行更新。无论我做什么,我都会不断收到此错误。我试过这个:Updating Nested Objects in Entity Framework 和这个:entity framework update nested objects
数据库操作预计会影响 1 行,但实际上会影响 0 行。自加载实体以来,数据可能已被修改或删除。有关理解和处理乐观并发异常的信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=527962。
“TypeName”:“Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException”
插入新行就可以了。但不更新。
public class BuyGroup
{
[Key]
public Guid Id { get; set; }
[Required]
[Column(TypeName = "nvarchar(150)")]
public string Name { get; set; }
public virtual ICollection<Item> Items { get; set; } = new List<Item>();
}
public class Item
{
[Key]
public Guid Id { get; set; }
[Required]
[Column(TypeName = "nvarchar(100)")]
public string Name { get; set; }
public BuyGroup BuyGroup { get; set; }
}
存储库:
public async Task<Guid> Save(Entities.BuyGroup model)
{
using (var dc = _dataContext())
{
// this is ok, i get existing item with Items collection populated
var existing = await Get(model.Id);
if (existing != null)
{
existing.Name = model.Name;
... // overwrite properties
existing.Items = model.Items; // overwrite Items colletion
dc.BuyGroups.Update(existing).State = EntityState.Modified;
}
else
{
await dc.BuyGroups.AddAsync(model);
}
// blows up here when existing != null
await dc.SaveChangesAsync();
}
}
编辑:
添加Get()方法
{
using (var dc = _dataContext())
{
return await dc.BuyGroups.FirstOrDefaultAsync(x => x.Id == id);
}
}
EDIT2:
使用相同的上下文仍然不能解决我的问题:
using (var dc = _dataContext())
{
var existing = await dc.BuyGroups.FirstOrDefaultAsync(x => x.Id == id); // same context
if (existing != null)
{
existing.Items.Add(new Item{ .....}):
dc.ByGroups.Entry(existing).State = EntityState.Modified;
} else {
await dc.BuyGroups.AddAsync(model);
}
await dc.SaveChangesAsync();
}
【问题讨论】:
-
如果你将
Items设为非虚拟,它会起作用吗? -
不 :(。不起作用
-
为什么两者都需要 1) dc.BuyGroups.Update(existing).State = EntityState.Modified; 2) 等待 dc.SaveChangesAsync();
-
用
dc.BuyGroups.Update(existing);替换dc.BuyGroups.Update(existing).State = EntityState.Modified; -
试过了。没用
标签: c# .net-core entity-framework-core