0

在 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 获取通用实体的替代方法是什么?

4

3 回答 3

0

类似的东西(T) m_context.Retrieve(typeof (T).Name, id, new ColumnSet())
这里

于 2013-04-05T11:06:40.293 回答
0

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

    public T GetEntityByID<T>(Guid guid) where T : Entity
    {
        return (T) (_organizationService.Retrieve((typeof(T)).Name, guid, new ColumnSet()));
    }
于 2014-05-14T12:35:38.777 回答
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);
}
于 2014-05-14T12:42:54.313 回答