LINQ to SQL: InsertOnSubmit() vs Add()

本文关键字:Add vs InsertOnSubmit to SQL LINQ | 更新日期: 2023-09-27 18:16:49

插入新子记录的最佳方法是:使用Add()InsertOnSubmit() ?这两种方法有什么区别吗?

InsertOnSubmit()示例:

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()示例:

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

LINQ to SQL: InsertOnSubmit() vs Add()

既然已经有了父ID,那么这样做会更有效:

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

这样,您就不必先检索父项,然后依靠对象跟踪来查找新项。