Reputation: 4125
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();
}
Upvotes: 6
Views: 15006
Reputation: 633
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.
Upvotes: 6