Reputation: 264
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?
Upvotes: 0
Views: 415
Reputation: 264
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;
Upvotes: 0
Reputation: 43880
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=...})
Upvotes: 1