1

Getting parent's ID is quite easy, as answered here: How can I get Id of inserted entity in Entity framework?

using (var context = new MyContext())
{
  context.MyEntities.AddObject(myNewObject);
  context.SaveChanges();

  int id = myNewObject.Id; // Yes it's here
}

However, I'm asking myself how I can get an ID of new created child entity (one-to-many), where a child has been add to the child collection, like:

existingParent.Children.Add(newChild);


public int Save(Parent parent)
{
   context.Update(parent);
   context.SaveChanges();    
   return ???;
}
Noor A Shuvo
  • 2,639
  • 3
  • 23
  • 48
Nearshore
  • 149
  • 3
  • 15

1 Answers1

0

It is unreasonable to return the id of the new created child in Save method.

For your current code, Save is not the only purpose to save Children property. Let's assume some scenario like below:

  1. Update Parenet without changing Children property, what is your expected return value for Save
  2. Update Parenet with adding multiple new Child, what is your expected return value
  3. Update Parenet with removing Child, what will it return

You may consider get the new Id outside public int Save(Parent parent) after calling context.SaveChanges();.

Demo Code:

        var parent1 = _db.Parent.Include(p => p.Children).FirstOrDefault(p => p.Id == 1);
        var child3 = new Child { Name = "N3"};
        var child4 = new Child { Name = "N4" };
        parent1.Children.Add(child3);
        parent1.Children.Add(child4);

        _db.Update(parent1);
        _db.SaveChanges();
        var childId3 = child3.Id;
        var childId4 = child4.Id;
Edward
  • 28,296
  • 11
  • 76
  • 121
  • Many thanks Tao Zhou - it works! If I may... one more question: if I use repository pattern and pass just the parent to the Save procedure (children added in the controller). How would it work that way? – Nearshore Sep 10 '18 at 08:53