3

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.

3 Answers 3

3

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.

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

Sign up to request clarification or add additional context in comments.

Comments

2

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();
   }

3 Comments

+1 Reusing the context here is a good idea. Using a stored procedure is an even better way to go. LINQ doesn't do bulk INSERT/UPDATE well as it really isn't intended to.
got it: no bulk operations in linq-to-sql; thanks for the tip on reusing the DC.
linq-to-sql will add a transaction itsself for each call to SubmitChanges so as long as you call it only once the transactionscope is useless. Also using an insert sp inside the foreach will not change it into a bulkinsert. In that case you need to move to SqlBulkCopy
0
List<Object> Obj = (Enter the List you want to pass)

foreach (var item in Obj)
{
    item.Get your desired value after the dot
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.