insert list of objects with linq-to-sql

16,776

Solution 1

Some quick improvements to consider..

a) Why creating datacontext for each iteration?

Using(Datacontext dc = new Datacontext())
{
    foreach(...)
    {

    }
   dc.SubmitChanges();
}

b) Creating a stored procedure for the Insert and using it will be good for performance.

c) Using Transaction Scope to undo insertions if any error encountered.

Using (TransactionScope ts = new TransactionScope())
   {
      dc.SubmitChanges();
   }

Solution 2

Why don't you use InsertAllOnSubmit() method.

Example:

IEnumerable<Post> _post = getAllNewPost();

 Using(Datacontext dc = new Datacontext())
    {
        dc.Posts.InsertAllOnSubmit(_post);
        dc.SubmitChanges();
     }

That's all you need.

////////////////////////

Share:
16,776
frenchie
Author by

frenchie

Started programming when I was 10. Never made it my profession but always programmed, mostly with Excel VBA for finance, and for some simple front-end web design in the early 2000's (ie. no jquery back then, what a pain it was with DHTML). One day, I get the idea of outsourcing the web development of my start-up: total cacacacacacacafukkkk! So: from VBA to C# .NET and Javascript in 5,000 pages of programming books, and lots of Stackoverflow! I think asking dumb questions is a smart way to learn. And as an internet entrepreneur, I've learned that what matters most is not knowing how to program but knowing what to program: discover the goyaPhone at www.goyaphone.eu

Updated on June 04, 2022

Comments

  • frenchie
    frenchie almost 2 years

    I have a list of objects that I'm inserting in a database with linq-to-sql. At the moment, I'm using a foreach loop that adds each element and that looks roughly like this:

    foreach (o in List<MyObjectModel)
    {
      using MyDataContext
      {
         TheLinqToSqlTableModel TheTable = new TheLinqToSqlTableModel();
    
         TheTable.Fieldname = o.Fieldname;
         .... repeat for each field
    
         MyDataContext.TheTablename.InsertOnSubmit(TheTable);
         MyDataContext.SubmitChanges();
    
      }
    }
    

    Is there a better way to insert a list of objects in a DB using linq-to-sql?

    Thanks for your suggestions.