what is entity reference definition

Damkulul picture Damkulul · Aug 7, 2017 · Viewed 7k times · Source

I'm trying to understand the use of entity reference (in crm 2011) I found online many examples of entity reference use, mostly with lookup fields, but I need an absoulte descreption. Is entity reference only for lookup field use ? can I use a simple entity to get my data? can entity replace entity reference ? My quesrion is not only about the difference between entityreference and entity it also about the definition of entityreference and why/where to use it. Can someone make this subject clear please.

Answer

Nicknow picture Nicknow · Aug 7, 2017

In Dynamics CRM development records are called entities and are made up of attributes. When an attribute is a lookup (i.e., a reference to another entity) it is of type EntityReference. The EntityReference type is necessary because it must convey both the logical name of the entity and the id (a Guid) of the specific record.

    IOrganizationService service = GetService(); //TODO: Implement GetService()

//From: https://msdn.microsoft.com/en-us/library/gg328149.aspx

Entity contact = new Entity("contact");
contact.Attributes["firstname"] = "ContactFirstName";
contact.Attributes["lastname"] = "ContactLastName";
Guid contactId = service.Create(contact);

Entity account = new Entity("account");
account["name"] = "Test Account1";
EntityReference primaryContactId = new EntityReference("contact", contactId);
account["primarycontactid"] = primaryContactId;

An Entity object cannot be used as an EntityReference because of the type difference. There is a method on Entity that returns an EntityReference, Entity.ToEntityReference().

IMPORTANT

The crucial thing about the EntityReference is that it contains both the logical name and the id of the record.

There are several areas in Dynamics CRM, such as when the Customer datatype is used, where a Lookup may refer to more than one entity type. In these situations there is no way for Dynamics CRM to rely on just a Guid as the record identifier.