How to mass insert/update in linq to sql?

Posted by chobo2 on Stack Overflow See other posts from Stack Overflow or by chobo2
Published on 2010-05-09T00:24:30Z Indexed on 2010/05/09 0:28 UTC
Read the original article Hit count: 649

Filed under:
|
|
|

Hi

How can I do these 2 scenarios.

Currently I am doing something like this

public class Repository
{
     private LinqtoSqlContext dbcontext = new LinqtoSqlContext();

   public void Update()
   {
   // find record
   // update record
   // save record ( dbcontext.submitChanges()
   }

   public void Insert()
   {
      // make a database table object ( ie ProductTable t = new ProductTable() { productname 
           ="something"}
      // insert record ( dbcontext.ProductTable.insertOnSubmit())
     // dbcontext.submitChanges();
   }
}

So now I am trying to load an XML file what has tons of records. First I validate the records one at a time. I then want to insert them into the database but instead of doing submitChanges() after each record I want to do a mass submit at the end.

So I have something like this

public class Repository { private LinqtoSqlContext dbcontext = new LinqtoSqlContext(); public void Update() { // find record // update record }

public void Insert() { // make a database table object ( ie ProductTable t = new ProductTable() { productname ="something"} // insert record ( dbcontext.ProductTable.insertOnSubmit()) }

public void SaveToDb() { dbcontext.submitChanges(); } }

Then in my service layer I would do like

for(int i = 0; i < 100; i++)
{
    validate();
    if(valid == true)
    {
       update();
       insert()
    }
}

SaveToDb();

So pretend my for loop is has a count for all the record found in the xml file. I first validate it. If valid then I have to update a table before I insert the record. I then insert the record.

After that I want to save everything in one go.

I am not sure if I can do a mass save when updating of if that has to be after every time or what.

But I thought it would work for sure for the insert one.

Nothing seems to crash and I am not sure how to check if the records are being added to the dbcontext.

© Stack Overflow or respective owner

Related posts about linq-to-sql

Related posts about c#