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();
}
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.
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.
When using LINQ to SQL, you insert new records by calling the InsertOnSubmit() method.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With