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();
}
reggaeguitar
  • 1,795
  • 1
  • 27
  • 48
koryakinp
  • 3,989
  • 6
  • 26
  • 56

1 Answers1

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.

Mike
  • 643
  • 3
  • 10