我如何 return 每个组织只有一个联系人?

How do I return only one contact per organization?

我必须 return 仅 return 成员帐户中的主要联系人,但我的查询是 return 组织内的所有成员。我试过重新排序并使用 Single() 之类的东西,但没有成功。我需要一种方法来放置一个 where 子句,说明我只想要一个帐户的主要联系人。

if ((!string.IsNullOrEmpty(organization)) && (!string.IsNullOrEmpty(city)) && state != null)
        {
            var corporatemembers = (from a in crmContext.bpt_membertypeSet
                                    where a.bpt_membertypename == "Member (Individual)" || a.bpt_membertypename == "Courtesy"
                                    || a.bpt_membertypename == "Affiliate" || a.bpt_membertypename == "Member"
                                    select new { a.Id }).ToList();

            foreach (var corporatemember in corporatemembers)
            {
                var directories = (from b in crmContext.AccountSet
                                   join a in crmContext.ContactSet
                                   on b.Id equals a.ParentCustomerId.Id
                                   where a.bpt_MemberTypeId.Id == corporatemember.Id
                                   where a.bpt_memberstatus == (int)bpt_memberstatus.Active
                                   where b.Name.Contains(organization)
                                   where a.Address1_City.Contains(city)
                                   where a.bpt_stateorusterritory.Value == state.Value
                                   select new { b.PrimaryContactId, b.EMailAddress1, a.Address1_City, b.Name, b.WebSiteURL, a.bpt_stateorusterritory }).ToList();

                foreach (var directory in directories.ToList().OrderBy(o => o.Name))
                {
                    var cityState = String.Empty;
                    if (directory.bpt_stateorusterritory != null)
                        cityState = directory.Address1_City + ", " + Utility.GetOptionSetValueLabel(crmContext, new Microsoft.Xrm.Sdk.Entity(Xrm.Contact.EntityLogicalName), "bpt_stateorusterritory", new Microsoft.Xrm.Sdk.OptionSetValue(directory.bpt_stateorusterritory.Value));
                    else
                        cityState = directory.Address1_City;
                    oMemberList.Add(new Members { FullName = directory.PrimaryContactId, FullNameEmail = directory.EMailAddress1, OrganizationName = directory.Name, OrganizationUrl = directory.WebSiteURL, CityState = cityState });
                }

            }
        }

此代码 return 如果搜索类别已全部填满,则为全部。我有 4 个子句适用于所有场景。但在整个事情结束时,我有:

oMembers.ToList()

谢谢

编辑:这里是样本数据,但输出是错误的。应该只有一个组织和一个联系人

我认为您在此处使用了错误的联接字段。这将 return 作为该帐户子级的所有联系人 - 这可能是您获得多个结果的原因。

on b.Id equals a.ParentCustomerId.Id

帐户的主要联系人字段是 primarycontactid,因此我建议您更新查询以引用该属性。