Microsoft Dynamics CRM 2011.按ID获取实体的通用方法

时间:2013-04-05 08:55:13

标签: dynamics-crm-2011 dynamics-crm

在CRM 4.0中,我的存储库中有通用方法:

public T GetEntityById(Guid id)
{
    var entities =
        from e in m_context.GetEntities(typeof (T).Name)
        where e.GetPropertyValue<Guid>(IdentityFieldName) == id
        select e;
    return (T) entities.FirstOrDefault();
}

但CRM 2011呢?错过了ICrmEntity和GetPropertyValue方法......

通过ID获取通用实体的替代方法是什么?

3 个答案:

答案 0 :(得分:0)

(T) m_context.Retrieve(typeof (T).Name, id, new ColumnSet())这样的东西 见here

答案 1 :(得分:0)

在寻找相同的答案时发现了这个问题,这就是我最终解决问题的方法。

    public T GetEntityByID<T>(Guid guid) where T : Entity
    {
        return (T) (_organizationService.Retrieve((typeof(T)).Name, guid, new ColumnSet()));
    }

答案 2 :(得分:0)

你真的想要使用ToEntity方法,而不是使用。有时typeof(T).Name会有大小写差异,所以我也写了一个帮助函数:

/// <summary>
/// Retrieves the Entity of the given type with the given Id, with the given columns
/// </summary>
/// <typeparam name="T">An early bound Entity Type</typeparam>
/// <param name="service">open IOrganizationService</param>
/// <param name="id">Primary Key of Entity</param>
/// <param name="columnSet">Columns to retrieve</param>
/// <returns></returns>
public static T GetEntity<T>(this IOrganizationService service, Guid id, ColumnSet columnSet)
    where T : Entity
{
    return service.Retrieve(EntityHelper.GetEntityLogicalName<T>(), id, columnSet).ToEntity<T>()
}

public static string GetEntityLogicalName<T>() where T : Entity
{
    return GetEntityLogicalName(typeof(T));
}

public static string GetEntityLogicalName(Type type)
{
    var field = type.GetField("EntityLogicalName");
    if (field == null)
    {
        if (type == typeof(Entity))
        {
            return "entity";
        }
        else
        {
            throw new Exception("Type " + type.FullName + " does not contain an EntityLogicalName Field");
        }
    }
    return (string)field.GetValue(null);
}