[英]LINQ to SQL: InsertOnSubmit() vs Add()
What is the best way to insert new child records: to use Add()
or InsertOnSubmit()
? 插入新子记录的最佳方法是:使用
Add()
或InsertOnSubmit()
? Is there any difference between those to approaches ? 方法之间有什么区别吗?
InsertOnSubmit()
example: 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()
example: 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();
}
Since you already have the parent ID, it would be more efficient to do this: 由于您已经拥有父ID,因此执行此操作会更有效:
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. 这样您就不会首先检索父级并依赖对象跟踪来查找新项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.