简体   繁体   中英

LINQ to SQL: InsertOnSubmit() vs Add()

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();
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM