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

如何在未知主键名称时使用Fetch XML过滤主键?

如何在FetchXML中无需知道主键名称过滤主键

好问题!在Dynamics 365/Dataverse环境中,确实没有直接支持attribute='primaryKey'的FetchXML语法,但有两种可靠的方式可以实现“不知道主键具体名称时过滤主键”的需求:

方法1:利用Dataverse主键的通用命名规则

Dataverse里所有标准实体和自定义实体的主键命名都遵循**[实体逻辑名称]id**的规则——比如账户(account)的主键是accountid,联系人(contact)的是contactid,自定义实体new_book的主键就是new_bookid。基于这个规则,你可以动态拼接主键字段名,直接写入FetchXML。

代码示例

[TestMethod]
public async Task ShouldRetrieveAnyEntity(OrganizationServiceProxy organizationServiceProxy)
{
    var entityName = "account";
    var entityGuid = "7004d3c1-3147-e811-a95e-000d3a10877d";
    
    // 动态生成主键字段名:实体逻辑名称 + "id"
    string primaryKeyField = $"{entityName}id";
    
    // 构建FetchXML
    string xml = $@"
    <fetch distinct='false' version='1.0' output-format='xml-platform' mapping='logical' aggregate='false'>
        <entity name='{entityName}'>
            <attribute name='name' /> <!-- 可替换为你需要查询的属性 -->
            <filter type='and'>
                <condition attribute='{primaryKeyField}' operator='eq' value='{entityGuid}' />
            </filter>
        </entity>
    </fetch>";
    
    // 执行查询
    EntityCollection results = await organizationServiceProxy.RetrieveMultipleAsync(new FetchExpression(xml));
    
    // 后续处理逻辑...
}

这种方式简单快捷,99%的场景下都能正常工作,因为Dataverse强制所有实体遵循这个主键命名规范。

方法2:通过实体元数据获取主键(更严谨)

如果需要100%的准确性(比如担心极端自定义场景,虽然几乎不存在),可以通过RetrieveEntityRequest获取实体的元数据,从中提取主键属性的逻辑名称。

代码示例

[TestMethod]
public async Task ShouldRetrieveAnyEntity(OrganizationServiceProxy organizationServiceProxy)
{
    var entityName = "account";
    var entityGuid = "7004d3c1-3147-e811-a95e-000d3a10877d";
    
    // 获取实体元数据,提取主键字段名
    RetrieveEntityRequest retrieveEntityReq = new RetrieveEntityRequest
    {
        EntityFilters = EntityFilters.Attributes,
        LogicalName = entityName,
        RetrieveAsIfPublished = true
    };
    
    RetrieveEntityResponse retrieveEntityResp = 
        (RetrieveEntityResponse)await organizationServiceProxy.ExecuteAsync(retrieveEntityReq);
    
    // 从元数据中获取主键属性的逻辑名称
    string primaryKeyField = retrieveEntityResp.EntityMetadata.PrimaryIdAttribute.LogicalName;
    
    // 构建FetchXML
    string xml = $@"
    <fetch distinct='false' version='1.0' output-format='xml-platform' mapping='logical' aggregate='false'>
        <entity name='{entityName}'>
            <attribute name='name' />
            <filter type='and'>
                <condition attribute='{primaryKeyField}' operator='eq' value='{entityGuid}' />
            </filter>
        </entity>
    </fetch>";
    
    EntityCollection results = await organizationServiceProxy.RetrieveMultipleAsync(new FetchExpression(xml));
}

这种方式虽然多了一步元数据查询,但能确保你拿到的是绝对正确的主键字段名,适合对准确性要求极高的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:57:56