问题
I am trying to update a Lookup field in CRM via the following code.
- Create a new entity Person
- Person contains a lookup field
HospitalOfBirth
from another entity Hospital - Value to be inserted: hospitalName
I referenced from online articles and drafted my code below.
Entity Person = new Entity("Person");
//do I set the value of the field by the following?
Person.Attributes[Person.HospitalOfBirth] = hospitalName;
Person.Attributes[Person.HospitalOfBirth] = new EntityReference("Hospital", Person.Id);
Person.Id = helper.GetOrganizationService().Create(Person);
May I know to assign a value to the lookup field HospitalOfBirth
in Person, and update it with hospitalName?
回答1:
You cannot set a lookup value by display name text, you need lookup Id (Foreign key) to achieve it.
If you just have the hospitalName
and not the hospitalId
, then you have to query the Hospital
entity for the GUID by doing RetrieveMultiple using FetchXml or QueryExpression by passing hospitalName
filter.
Person.Attributes[Person.HospitalOfBirth] = new EntityReference("Hospital", Hospitalid);
回答2:
Entity Person = new Entity("Person");
Person.Attributes[Person.HospitalOfBirth] = new EntityReference("Hospital", Person.Id);
Person.Id = **<<Guid of the Person record you need to update>>**
helper.GetOrganizationService().Update(Person);
You need to provide the guid of the record you want to update in the entity object.
Hope this helps !!!
来源:https://stackoverflow.com/questions/61287388/how-to-set-value-of-lookup-field-in-a-new-entity-in-crm-using-c-sharp