Convert EntityReference to Entity

2020-05-27 03:46发布

Does anyone know how can Convert EntityReference to Entity.

protected override void Execute(CodeActivityContext executionContext)
{
    [Input("Email")]
    [ReferenceTarget("email")]
    public InArgument<Entity> EMail { get; set; }


    Entity MyEmail = EMail.Get<Entity>(executionContext);

This give me an error. Cannot convert this.

3条回答
Anthone
2楼-- · 2020-05-27 04:09

Entity and EntityReference is different. The EntityReference is a reference for a record which contains the GUID and the logical name of entity. You have to get the entity accessing through guid and logical name. Something like that:

service.Retrieve(logicalname, guid, new ColumnSet(columns));
查看更多
疯言疯语
3楼-- · 2020-05-27 04:12

The shortest answer to your questions is to query the database for the entity that's pointed out (referred to) by the entity reference. I've always viewed entity references as (rough) equivalent to the pointers in C++. It's got the address to it (guid) but you need to de-reference it in order to get to the honey. You do that like this.

IOrganizationService organization = ...;
EntityReference reference = ...;

Entity entity = organization.Retrieve(reference.LogicalName, reference.Id, 
  new ColumnSet("field_1", "field_2", ..., "field_z"));

When I do a lot of converting from EntityReference to Entity, I deploy the extension method with optional parameter for the fields.

public static Entity ActualEntity(this EntityReference reference,
  IOrganizationService organization, String[] fields = null)
{
  if (fields == null)
    return organization.Retrieve(reference.LogicalName, reference.Id, 
      new ColumnSet(true));
  return organization.Retrieve(reference.LogicalName, reference.Id, 
    new ColumnSet(fields));
}

You can read more and compare EntityReference and Entity.

查看更多
我只想做你的唯一
4楼-- · 2020-05-27 04:30

An EntityReference is just the logicalName, name, and id of the entity. So to get an Entity, you just need to create the entity using the properties of the EntityReference.

Here is an Extension Method that performs that for you:

public static Entity GetEntity(this EntityReference e)
{
    return new Entity(e.LogicalName) { Id = e.Id };
}

Don't forget that none of the other attributes of the entity will be populated. If you want the attributes you'll need to query for them:

public static Entity GetEntity(this IOrganizationService service, EntityReference e)
{
    return service.Retrieve(e.LogicalName, e.Id, new ColumnSet(true));
}

And if you like @Konrad's Field answer, make it a params array and it is nicer to call

public static Entity GetEntity(this IOrganizationService service, EntityReference e, 
   params String[] fields)
{
    return service.Retrieve(e.LogicalName, e.Id, new ColumnSet(fields));
}
查看更多
登录 后发表回答