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

我们两清 提交于 2021-02-11 14:55:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!