Search code examples
c#dynamics-crm-2011dynamics-crmcrmdynamics-crm-2013

CRM SDK update record with related lookup


I have an entity (Server) which has a 1:N lookup field on another entity (Host). From the SDK I can easily create records:

foreach (VirtualMachine vm in vmObjects)
        {
            new_server newServer = new new_server();
            newServer.new_name = vm.Name;
            newServer.new_Memory = vm.Memory;
            newServer.new_new_host_new_server_Host = xrm.new_hostSet.Where(x => x.new_HostSCVMMId == vm.HostId).Single();
            xrm.AddObject(newServer);
        }
        xrm.SaveChanges();

The new records has the correct "Host" lookup related field set. Now, when I try to update the records:

foreach (VirtualMachine vm in vmObjects)
        {
            new_server updateServer = xrm.new_serverSet.FirstOrDefault(x => x.new_VMId == vm.VMId);
            if (updateServer != null)
            {
                updateServer.new_name = vm.Name;
                updateServer.new_Memory = vm.Memory;
                updateServer.new_new_host_new_server_Host = xrm.new_hostSet.Where(x => x.new_HostSCVMMId == vm.HostId).Single();
                xrm.UpdateObject(updateServer);
            }
        }
        xrm.SaveChanges();

It gives the following error (if I comment out the line with the new_host_new_server_Host then it will update eg. memory correctly.

An unhandled exception of type 'System.InvalidOperationException' occurred in Microsoft.Xrm.Sdk.dll
Additional information: The collection is read-only.

Why can't I update the Host property of the record just because it is a lookup field?


Solution

  • You will want to set the property with the type EntityReference instead of the property you are setting.