簡體   English   中英

Microsoft Dynamics CRM2011。通過ID獲取實體的通用方法

[英]Microsoft Dynamics CRM 2011. Generic method to get entity by ID

在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方法的ICrmEntity ...

什么是通過ID獲得通用實體的替代方法?

(T) m_context.Retrieve(typeof (T).Name, id, new ColumnSet())
這里

尋找相同答案時發現了這個問題,這就是我最終解決它的方式。

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

您確實希望使用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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM