CRM Linq 查找具有 0 children 的所有 parents

CRM Linq find all parents that have 0 children

我如何找到(最好使用 CRM Linq)parent 个具有 0 children 个实体。例如,我怎样才能找到所有有 0 个联系人的帐户。

您要找的是左外连接。不幸的是,这在使用 LINQ 的 CRM 中是不可能的。但是,您可以使用查询表达式或 FetchXML 来完成。

这里有一个 link 可以帮助你: https://community.dynamics.com/crm/b/gonzaloruiz/archive/2014/02/23/all-about-outer-join-queries-in-crm-2011-and-crm-2013

如果您要使用我推荐的查询表达式路由,那么以下代码将会很有用

var entityAlias = "con";
var query = new QueryExpression
        {
            EntityName = "account",
            ColumnSet = new ColumnSet(true),
            Criteria =
            { 
                FilterOperator = LogicalOperator.And,
                Conditions =
                {
                    new ConditionExpression(entityAlias, "contactid",ConditionOperator.Null)
                }
            }
            LinkEntities =
            {
                new LinkEntity
                {
                    EntityAlias = entityAlias,
                    LinkFromEntityName = "account",
                    LinkFromAttributeName = "accountid",
                    LinkToEntityName = "contact",
                    LinkToAttributeName = "parentcustomerid",
                    Columns = new ColumnSet("parentcustomerid", "contactid"),
                    JoinOperator = JoinOperator.LeftOuter,
                }
            },
        };

var response = service.RetrieveMultiple(query);
var accounts = response.Entities;

在这段代码中我没有限制列,这会降低性能,你应该只 return 需要的列。

如果要 returned 超过 5000 条记录,那么您将需要使用分页并循环查询以查找所有实体, 这可以在这里找到:

https://msdn.microsoft.com/en-us/library/gg327917.aspx

但是,如果您确定要使用 LINQ,则可以使用以下代码:

public static IEnumerable<Account> FindAccountsWithNoContacts()
{
   var contactRelationship = new Relationship("contact_customer_accounts");
   foreach(var account in XrmContext.AccountSet)
   {
      XrmContext.LoadProperty(contactRelationship);
      if(!account.RelatedEntities.ContainsKey(contactRelationship)
      yield return account;

   }  
}

我的 LINQ 代码问题是所有实体,包括帐户实体和联系人实体,都将加载到内存中。对于大型实体集,这可能会导致 OutOfMemoryException,而查询表达式路由会将查询传递给 Dynamics 服务器执行;这应该使代码的执行速度更快。