locked
Linq: How do I create a loop that saves at the end of each loop sequence? RRS feed

  • Question

  • The code below loops through 50 Contact records and updates each record with migrated = true.

    The "actual" Saving occurs only when the loop has gone through all 50 records.

    However, if record number 19 fails to create in the Target System, the loop breaks and records 1 to 18 will never get updated (with migrated = true) in the Source System.

    How do I create a loop that saves at the end of each loop sequence?

    var sourceconatcts = (
        from c in xrm.ContactSet
        join i in xrm.IncidentSet on c.ContactId equals i.CustomerId.Id
        where (c.new_migrated != true)
        select c).Distinct().Take(50).ToList();
        
            foreach (var contact in sourceconatcts)
            {
                // Code that creates a record in the target system has been removed
                // Update Source System that record has been migrated successfully
                contact.new_migrated = true;
                xrm.UpdateObject(contact);
            };
        xrm.SaveChanges();


    Saturday, January 18, 2014 12:22 PM

All replies

  • Just put the save call inside the loop.  

    var sourceconatcts = (
        from c in xrm.ContactSet
        join i in xrm.IncidentSet on c.ContactId equals i.CustomerId.Id
        where (c.new_migrated != true)
        select c).Distinct().Take(50).ToList();
        
            foreach (var contact in sourceconatcts)
            {
                // Code that creates a record in the target system has been removed
                // Update Source System that record has been migrated successfully
                contact.new_migrated = true;
                xrm.UpdateObject(contact);
                xrm.SaveChanges();
            }

    You also might want to put a try/catch inside the loop so if one record fails, the loop will keep continuing.

    var sourceconatcts = (
        from c in xrm.ContactSet
        join i in xrm.IncidentSet on c.ContactId equals i.CustomerId.Id
        where (c.new_migrated != true)
        select c).Distinct().Take(50).ToList();
        
            foreach (var contact in sourceconatcts)
            {
                try 
                {
                   contact.new_migrated = true;
                   xrm.UpdateObject(contact);
                   xrm.SaveChanges();
                }
                catch (Exception ex) 
                {
                   // probably want to use some sort of logging mechanism here so you know a record failed
                }
            }


    Blake Scarlavai - http://mscrmdev.blogspot.com/ - Sonoma Partners - http://www.sonomapartners.com/ - Follow @bscarlav
    CRM 2011 JavaScript Model Generator - CRM 2011 Appender for log4net



    Saturday, January 18, 2014 7:35 PM