Trying to perform an update on an entity with nested list. I keep getting this error no matter what I do. I've tried this: Updating Nested Objects in Entity Framework and this: entity framework update nested objects
Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.
"TypeName": "Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException"
Inserting a new row works just fine. But not update.
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; }
}
Repository:
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();
}
}
EDIT:
Adding Get()
method
{
using (var dc = _dataContext())
{
return await dc.BuyGroups.FirstOrDefaultAsync(x => x.Id == id);
}
}
EDIT2:
Using the same context still does not solve my issue:
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();
}