Reputation: 773
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?
Upvotes: 0
Views: 984
Reputation: 773
Thanks BlueSam,
I finally got it:
Guid hostGuid = xrm.new_hostSet.Where(x => x.new_HostSCVMMId == vm.HostId).Single().Id;
updateServer.new_Host = new Microsoft.Xrm.Client.CrmEntityReference("new_host", hostGuid);
Upvotes: 1
Reputation: 1888
You will want to set the property with the type EntityReference instead of the property you are setting.
Upvotes: 1