Cannot Update Contact while looping through using C# and Linq RRS feed

  • Question

  • The remmened out does not work, however, the foreach below works fine.

    It seems a bit unnecessary to open the Contact twice for updating.

    using System;
    using System.Linq;
    using Xrm;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk;
    namespace CSEM_migration
        public partial class modifycontacts : System.Web.UI.Page
            protected void Page_Load(object sender, EventArgs e)
                var xrm = new XrmServiceContext("Xrm");
                var GetContacts = xrm.ContactSet
                    .Where(c => c.StateCode.Value == 0)
                    .Where(c => c.OwnerId.Equals("26489806-250d-e211-8af5-3c4a92dbd83d"))
                    .Where(c => c.new_csem_id.Equals(null))
                //foreach (Contact contact in GetContacts)
                //    contact.new_csem_id = contact.ContactId.ToString();
                //    xrm.UpdateObject(contact);
                foreach (var contact in GetContacts)
                     ColumnSet cols = new ColumnSet(new String[] { "contactid", "description" });
                     Contact retrievedContact = (Contact)xrm.Retrieve("contact", new Guid(contact.ContactId.ToString()), cols);
                     retrievedContact.new_csem_id = contact.ContactId.ToString();

    Monday, December 30, 2013 2:38 PM


  • Hi,

    All entities returned from a LINQ query are tracked by the service context. When you retrieve a record with a LINQ query the context would track that entity. You can then work with data to create new entities, create related entities, and modify existing entities, but you must call the SaveChanges method on tracked entities to commit changes to the CRM server.

    foreach (Contact contact in GetContacts) { contact.new_csem_id = contact.ContactId.ToString(); xrm.UpdateObject(contact); };



    • Marked as answer by Allen Campbell Tuesday, December 31, 2013 8:51 AM
    Monday, December 30, 2013 7:52 PM