Search code examples
c#dynamics-crmcrmlookupmicrosoft-dynamics

How to set value of lookup field in a new entity in CRM using C#


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?


Solution

  • 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);