Should ToEntity <T> be used instead of a role?

Xrm Sdk defines the method ToEntity<T>. I always used it to get my early related entities from CRM. Today I looked through some code and saw that the entities just got:

var contact = service.Retrieve("contact", id, new ColumnSet()) as Contact;

I did not even know that it was possible. Do I still need a ToEntity call?

+4
source share
2 answers

In a way, this is not a specific cast, its transformation and transformation behave somewhat differently than direct casting.

As

as NULL... as . , , null .

, Contact - , CrmSvcUtil, . public partial class Contact : Microsoft.Xrm.Sdk.Entity service.Retrieve IOrganizationService.Retrieve, Entity.

Contact - Entity. (. #?). Entity Contact, , .

GeneratedCode CrmSvcUtil , CRM .

var entity = new Entity();

Console.WriteLine($"Type of local entity: {entity.GetType()}");

Console.WriteLine($"Local entity as Contact is null? {entity as Contact == null}");

:

Type of local entity: Microsoft.Xrm.Sdk.Entity
Local entity as Contact is null? True

, Retrieve Entity, Contact, (var contact = service.Retrieve("contact", id, new ColumnSet()) as Contact;)?

, . , GeneratedCode CrmSvcUtil , Retrieve Entity.

GeneratedCode CrmSvcUtil :

CrmServiceClient service = new CrmServiceClient(ConfigurationManager.ConnectionStrings["Crm"].ConnectionString);

Contact c = new Contact()
{
    LastName = "Test"
};

Guid contactId = service.Create(c);

var response = service.Retrieve("contact", contactId, new ColumnSet());

Console.WriteLine($"Type of response from CRM: {response.GetType()}");

Console.WriteLine($"Response from CRM as contact is null? {response as Contact == null}");

:

Type of response from CRM: Contact
Response from CRM as contact is null? False

:

CrmServiceClient service = new CrmServiceClient(ConfigurationManager.ConnectionStrings["Crm"].ConnectionString);

Entity c = new Entity("contact");
c["lastname"] = "Test";

Guid contactId = service.Create(c);

var response = service.Retrieve("contact", contactId, new ColumnSet());

Console.WriteLine($"Type of response: {response.GetType()}");

:

Type of response: Microsoft.Xrm.Sdk.Entity

. , , Retrieve Contact, (, (Contact)service.Retrieve(...)) (as). , ToEntity, . . , , , , .

:

public T ToEntity<T>() where T : Entity
{
    if (typeof(T) == typeof(Entity))
    {
        Entity entity = new Entity();
        this.ShallowCopyTo(entity);
        return entity as T;
    }
    if (string.IsNullOrWhiteSpace(this._logicalName))
    {
        throw new NotSupportedException("LogicalName must be set before calling ToEntity()");
    }
    string text = null;
    object[] customAttributes = typeof(T).GetCustomAttributes(typeof(EntityLogicalNameAttribute), true);
    if (customAttributes != null)
    {
        object[] array = customAttributes;
        int num = 0;
        if (num < array.Length)
        {
            EntityLogicalNameAttribute entityLogicalNameAttribute = (EntityLogicalNameAttribute)array[num];
            text = entityLogicalNameAttribute.LogicalName;
        }
    }
    if (string.IsNullOrWhiteSpace(text))
    {
        throw new NotSupportedException("Cannot convert to type that is does not have EntityLogicalNameAttribute");
    }
    if (this._logicalName != text)
    {
        throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Cannot convert entity {0} to {1}", new object[]
        {
            this._logicalName,
            text
        }));
    }
    T t = (T)((object)Activator.CreateInstance(typeof(T)));
    this.ShallowCopyTo(t);
    return t;
}
+3

, CRM 2011

ColumnSet cols = new ColumnSet(new String[] { "name", "address1_postalcode", "lastusedincampaign", "versionnumber" });
Account retrievedAccount = (Account)_serviceProxy.Retrieve("account", _accountId, cols);
Console.Write("retrieved ");

EnableProxyTypes(); IOrganizationService. , , , Entity (, Entity, , ). CRM.

ToEntity < > (), - :

var account = new Entity("account");
var earlyBoundAccount = account as Account; //this will result in NULL

, Entity (, PostImage), ToEntity, .

UPDATE: , EnableProxyTypes - DataContractSerializerOperationBehavior, IDataContractSurrogate / ( , , ). CRM, , :

object IDataContractSurrogate.GetDeserializedObject(object obj, Type targetType)
{
    bool supportIndividualAssemblies = this._proxyTypesAssembly != null;
    OrganizationResponse organizationResponse = obj as OrganizationResponse;
    if (organizationResponse != null)
    {
        Type typeForName = KnownProxyTypesProvider.GetInstance(supportIndividualAssemblies).GetTypeForName(organizationResponse.ResponseName, this._proxyTypesAssembly);
        if (typeForName == null)
        {
            return obj;
        }
        OrganizationResponse organizationResponse2 = (OrganizationResponse)Activator.CreateInstance(typeForName);
        organizationResponse2.ResponseName = organizationResponse.ResponseName;
        organizationResponse2.Results = organizationResponse.Results;
        return organizationResponse2;
    }
    else
    {
        Entity entity = obj as Entity;
        if (entity == null)
        {
            return obj;
        }
        Type typeForName2 = KnownProxyTypesProvider.GetInstance(supportIndividualAssemblies).GetTypeForName(entity.LogicalName, this._proxyTypesAssembly);
        if (typeForName2 == null)
        {
            return obj;
        }
        Entity entity2 = (Entity)Activator.CreateInstance(typeForName2);
        entity.ShallowCopyTo(entity2);
        return entity2;
    }
}

, KnownProxyTypes Activator. - IOrganizationService, - (, , - , IOrganizationService, , , 100%)

+3

Source: https://habr.com/ru/post/1677349/


All Articles