简体   繁体   中英

EF Core 3.1 Removing parent entity with child relations + save changes + reuse same child id in new parent = concurrent exception

Situation before doing anything:

class Parent: { int ParentId, Child Children: [] }
class Child: { int ChildId, int ParentId }
db.Parents: [{ ParentId: 1, Children:[ ChildId: 10, ParentId: 1] })
db.Children: [{ ChildId: 10, ParentId: 1 })

I'm trying to do something like:

...
using var db = new DB();
var entity = await db.Parents.FirstOrDefaultAsync(e => e.ParentId == 1);
db.WorkdayResults.Remove(entity);
await db.SaveChangesAsync(); // After saving: db.Parents and db.Children will be empty
var entry = await db.Parents.AddAsync(new Parent{});
// entry.Entity.Children.Add(new Child {}); // This works
entry.Entity.Children.Add(new Child { ChildId: 1 }); // This does not work
await db.SaveChangesAsync() // Getting concurrent exception here
...

I don't want to change the logic, such: saving parent first, create new context and save then child with its old ChildId. So do you guys have any good solution for this? Is this EF Core or Devart MySql feature?

You have an error. You need ParentId key to add a child. And since you db is empty now try to use this:

[]Child children= { new Child {ParentId=1, ChildrenId=10}}
db.Parents.Add(new Parent { ParentId=1 , Chilren=  children}; 

Or if your dbcontext is configured right way you can try inverse:

db.Children.Add( new Child { ChidrentId=10, Parent= new Parent {ParentId=1}}

But if your Ids are auto-seeds and your dbcontext is configured the right way it would be enough:


db.Parents.Add(new Parent { Children= { new Child {}} }; 

Only if you have a parent object already, you can use like this:

db.Children.Add( new Child {ParentId=...,ChildId=...})

Like the topic says that it was concurrent exception, so I debugged and found that for some reason EF core did set the entity state as 'Modified' if I was using old ChildId, even if the old entity didn't exists on the context anymore. So here's the very simply solution:

db.Entry(childEntity).State = EntityState.Added;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM