5

What is the best way to insert new child records: to use Add() or InsertOnSubmit() ? Is there any difference between those to approaches ?

InsertOnSubmit() example:

using (DataContext db = new DataContext())
{
   Parent p = db.Parents.Where(q => q.ID == SomeID).SingleOrDefault();
   Child c = new Child();
   c.ForeignKeyID = p.ID;
   db.InsertOnSubmit(c);
   db.SubmitChanges();
}

Add() example:

using (DataContext db = new DataContext())
{
   Parent p = db.Parents.Where(q => q.ID == SomeID).SingleOrDefault();
   Child c = new Child();
   p.Add(c);
   db.SubmitChanges();
}
3
  • well its up to you - whats more clear to you and your code? Aug 5, 2014 at 17:09
  • How is Parent.Add defined? Aug 5, 2014 at 17:10
  • 1
    @MarcinJuraszek, it looks like OP made a typo, and is talking about EntityCollection.Add
    – Andrei
    Aug 5, 2014 at 17:18

1 Answer 1

6

Since you already have the parent ID, it would be more efficient to do this:

using(DataContext db = new DataContext())
{
   Child c = new Child();
   c.ForeignKeyID = SomeID;
   db.InsertOnSubmit(c);
   db.SubmitChanges();
}

This way you're not retrieving the parent first and relying on object tracking to find the new item.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.