Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 754
koryakinp Avatar asked Aug 05 '14 17:08

koryakinp


People also ask

Is LINQ to SQL obsolete?

LINQ to SQL was the first object-relational mapping technology released by Microsoft. It works well in basic scenarios and continues to be supported in Visual Studio, but it's no longer under active development.

How to insert data IN database using LINQ to SQL IN c#?

Use the following procedure to insert a row into the database: Create a new object that includes the column data to be submitted. Add the new object to the LINQ to SQL Table collection associated with the target table in the database. Submit the change to the database.

Which method do you use in order to insert a record into the database with LINQ?

When using LINQ to SQL, you insert new records by calling the InsertOnSubmit() method.

What is LINQ to DB?

LINQ to DB is the fastest LINQ database access library offering a simple, light, fast, and type-safe layer between your POCO objects and your database.


1 Answers

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.

like image 183
Mike Avatar answered Oct 09 '22 22:10

Mike