我正在使用 fetchXML 连接两个实体,但只能获取第一个列表的结果。我可能犯了一个愚蠢的错误,但这让我浪费了几个小时。
var query = @"
<fetch version='1.0' mapping='logical' distinct='true'>
<entity name='contact'>
<all-attributes />
<link-entity name='new_custom' from='new_contactid' to='contactid' link-type='inner'>
<all-attributes />
</link-entity>
</entity>
</fetch>
";
var fe = new FetchExpression(query);
var result = service.RetrieveMultiple(fe);
// This contact entity is properly filled
var contact = result.Entities.First().Cast<Contact>();
// This relationship is null, that's unexpected!
var custom = contact.new_contact_new_custom;
// Also null (not sure if this should work)
var related = contact.GetRelatedEntity<new_custom>("new_contact_new_custom", null);
我确实看到在 Contact 实体的 Attributes
和 FormattedValues
属性中检索到了正确的数据。但是为什么没有正确建立关系呢?以及如何将此数据转换为正确的“自定义”实体类型?
最佳答案
首先:您确定您的查询返回早期绑定(bind)对象吗?在我下面的示例中,我假设您获得了 Entity 对象(后期绑定(bind)),但对于这个示例来说,这并没有太大的区别。
查询的响应基本上是您所请求类型的实体对象的普通表,在本例中为“联系人”。连接实体的字段也可以添加到此表中,但它们被包装在 AliasedValue
中对象。它们的列名以 LinkEntity
为前缀别名以防止名称冲突。
您的线路var contact = result.Entities.Cast<Contact>();
建议变量 contact
类型为 Contact
, 但它实际上是一个 IEnumerable<Contact>
. (使用 var
并不总是那么有用。)出于这个原因,我怀疑你的最后两行甚至没有编译。
在下面的示例中,获取查询被发送到 Organization.svc 端点。 (注意别名属性。)然后实体“new_custom”的字段“new_name”取自查询结果集的第一行。
var fetchXml = @"
<fetch version='1.0' mapping='logical' distinct='true'>
<entity name='contact'>
<all-attributes />
<link-entity name='new_custom' alias='nc' from='new_contactid' to='contactid' link-type='inner'>
<all-attributes />
</link-entity>
</entity>
</fetch>
";
var query = new FetchExpression(fetchXml);
var response = service.RetrieveMultiple(query);
var contact = response.Entities[0];
var customField = contact.GetAttributeValue<AliasedValue>("nc.new_name");
string name = customField != null ? (string)customField.Value : null;
关于c# - 使用 FetchXML 获取(强类型)相关实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22270406/