Connecting Tech Pros Worldwide Forums | Help | Site Map

How to bulk update/insert using Linq

Newbie
 
Join Date: Aug 2009
Posts: 1
#1: Aug 3 '09
Hi, I have recently developed a C# application using Linq. I am getting from an external database a list of profiles I need to process, some are new and some are already in the database, and need to be updated. What I do today is go over the profile list and check each profile if such exists I update otherwise I insert - this solution is working fine.

I am sure there is a way to use bulk insert/update something like UPDATE ON DUPLICATE, this way I can save time since the files I get are huge and bulk insert/update is known to have better performance. I would like to avoid the iteration I am now using.

insertall doesn't work for already stored rows, I need the combination of both update and insert

Here is my code, Your help is highly appreciated.

Expand|Select|Wrap|Line Numbers
  1. foreach (Profile tmpProfile in profiles)
  2.             {
  3.                 try
  4.                 {                      
  5.                     var matchedProfile = (from c in db.ProfileEntities
  6.                                           where c.ProfileId == tmpProfile.Id
  7.                                           select c).SingleOrDefault();
  8.  
  9.                     if (matchedProfile == null)
  10.                     {
  11.                         //Insert
  12.                         db.ProfileEntities.InsertOnSubmit(EntityMapper.ToEntity(tmpProfile));
  13.  
  14.                     }
  15.                     else
  16.                     {
  17.                         //Update
  18.                         EntityMapper.ToEntity(ref matchedProfile, tmpProfile);                           
  19.  
  20.                     }                                               
  21.                 }
  22.                 catch (System.Data.SqlServerCe.SqlCeException sqlExec)
  23.                 {                       
  24.  
  25.                 }
  26.                 catch (Exception e)
  27.                 {
  28.  
  29.                 }
  30.             }
  31.  
  32.             db.SubmitChanges();

MrMancunian's Avatar
Expert
 
Join Date: Jul 2008
Location: Utrecht, The Netherlands
Posts: 283
#2: Aug 4 '09

re: How to bulk update/insert using Linq


For as far as I know, LINQ can only be used to select; not to insert and update.
Reply

Tags
bulk, insert, linq, update