You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Service Client依据属性从Dynamics 365获取实体?

通过指定属性获取实体的可行实现方案

因为ServiceClient.Retrieve必须传入实体Id才能获取数据,要通过属性匹配获取实体,推荐以下几种实用方案:

方案1:先查询Id再调用Retrieve

通过RetrieveMultiple方法构造条件查询,先拿到符合属性要求的实体Id,再用Id调用Retrieve获取完整实体。

示例代码:

// 构造查询条件,以账号实体为例,匹配名称为"Contoso"的记录
var accountQuery = new QueryExpression("account")
{
    ColumnSet = new ColumnSet("accountid"), // 仅需查询Id列,提升效率
    Criteria = new FilterExpression
    {
        Conditions = { new ConditionExpression("name", ConditionOperator.Equal, "Contoso") }
    },
    TopCount = 1 // 限制只返回第一条匹配结果,避免多数据冲突
};

// 执行查询获取结果
var queryResult = serviceClient.RetrieveMultiple(accountQuery);

// 提取Id并调用Retrieve获取完整实体
if (queryResult.Entities.Any())
{
    var targetAccountId = queryResult.Entities.First().Id;
    var fullAccount = serviceClient.Retrieve("account", targetAccountId, new ColumnSet(true));
}

注意:如果业务场景允许多个匹配结果,需要额外处理筛选逻辑,比如按创建时间排序取最新的。

方案2:封装自定义方法简化调用

自己封装一个工具方法,把“查询Id+调用Retrieve”的逻辑整合起来,对外只需要传入实体名、属性条件和要获取的列,不用重复写查询代码。

示例代码:

public Entity RetrieveEntityByAttribute(IOrganizationService service, string entityLogicalName, string attrName, object attrValue, ColumnSet columns)
{
    var query = new QueryExpression(entityLogicalName)
    {
        ColumnSet = new ColumnSet($"{entityLogicalName}id"), // 动态获取Id列名
        Criteria = new FilterExpression
        {
            Conditions = { new ConditionExpression(attrName, ConditionOperator.Equal, attrValue) }
        },
        TopCount = 1
    };

    var result = service.RetrieveMultiple(query);
    return result.Entities.Any() ? service.Retrieve(entityLogicalName, result.Entities.First().Id, columns) : null;
}

// 调用示例:通过邮箱获取联系人实体
var targetContact = RetrieveEntityByAttribute(serviceClient, "contact", "emailaddress1", "user@example.com", new ColumnSet(true));

方案3:直接用RetrieveMultiple返回完整实体

如果不需要严格依赖Retrieve方法,可以直接在RetrieveMultiple的ColumnSet中指定所有需要的字段,查询后直接返回结果实体,省去二次调用的步骤,效率更高。

示例代码:

// 直接查询符合手机号条件的联系人完整信息
var contactQuery = new QueryExpression("contact")
{
    ColumnSet = new ColumnSet(true), // 获取所有字段,也可以指定具体列如"fullname","mobilephone"
    Criteria = new FilterExpression
    {
        Conditions = { new ConditionExpression("mobilephone", ConditionOperator.Equal, "13800138000") }
    },
    TopCount = 1
};

var targetContact = serviceClient.RetrieveMultiple(contactQuery).Entities.FirstOrDefault();

内容的提问来源于stack exchange,提问作者Shahin Jabbarov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 23:23:30