Dynamics CRM 2011 编程系列(18):插件中的Read操作

    在前两节中我们分别涉及到了Read操作,一种是通过FetchExpression来实现的Read操作,另一种是通过QueryExpression来实现的Read操作。FetchExpression的功能比QueryExpression的功能要强大,它支持聚合查询。我们来看几个小例子吧。

涉及的实体

  客户

    商机


需要实现的需求

1.用QueryExpression查询所有姓王的客户

2.用QueryExpression查询所有姓王的客户的商机

3.用FetchExpression查询当前系统中的所有客户数量

4.用QueryExpression分页查询记录

5.用FetchExpression分页查询记录




实现步骤
Dynamics CRM 2011 编程系列(18):插件中的Read操作_第1张图片

图1

Dynamics CRM 2011 编程系列(18):插件中的Read操作_第2张图片

图2 用QueryExpression查询“姓王的客户记录”

Dynamics CRM 2011 编程系列(18):插件中的Read操作_第3张图片

图3

Dynamics CRM 2011 编程系列(18):插件中的Read操作_第4张图片

图4 用QueryExpression查询“姓王的客户下的商机”

Dynamics CRM 2011 编程系列(18):插件中的Read操作_第5张图片

图5 在使用FetchExpression查询前,必须生成Fetch文件

Dynamics CRM 2011 编程系列(18):插件中的Read操作_第6张图片

图6 通过系统的高级查找来生成Fetch文件

Dynamics CRM 2011 编程系列(18):插件中的Read操作_第7张图片

图7

Dynamics CRM 2011 编程系列(18):插件中的Read操作_第8张图片

图8 导出Fetch文件

Dynamics CRM 2011 编程系列(18):插件中的Read操作_第9张图片

图9

Dynamics CRM 2011 编程系列(18):插件中的Read操作_第10张图片

图10 将Fetch修改成聚合查询

Dynamics CRM 2011 编程系列(18):插件中的Read操作_第11张图片

图11 实现Fetch聚合查询后得到的结果

Dynamics CRM 2011 编程系列(18):插件中的Read操作_第12张图片

图12  QueryExpression和FetchExpression默认情况下最多返回5000条记录

Dynamics CRM 2011 编程系列(18):插件中的Read操作_第13张图片

图13

Dynamics CRM 2011 编程系列(18):插件中的Read操作_第14张图片

图14




使用到的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;

namespace Plugin18
{
    public class QueryOrFetch : IPlugin
    {

        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = factory.CreateOrganizationService(null);
            EntityCollection result = null;
            string msg = string.Empty;

            #region 通过QueryExpression获取所有姓王的客户记录

            QueryExpression query = new QueryExpression();
            query.EntityName = "account";
            query.ColumnSet = new ColumnSet { AllColumns = true };
            query.Criteria = new FilterExpression();

            ConditionExpression conditionExp = new ConditionExpression();
            conditionExp.AttributeName = "name";
            conditionExp.Operator = ConditionOperator.BeginsWith;
            conditionExp.Values.Add("王");

            query.Criteria.Conditions.Add(conditionExp);

            result = service.RetrieveMultiple(query);

            foreach (Entity tmp in result.Entities)
            {
                msg += string.Format("Id:{0},Name:{1},Owner:{2}<br/>", tmp.Id, tmp["name"], ((EntityReference)tmp["ownerid"]).Name);
            }

            throw new InvalidPluginExecutionException(OperationStatus.Canceled, msg);

            #endregion

            #region 用QueryExpression查询所有姓王的客户的商机记录
            QueryExpression query = new QueryExpression();
            query.EntityName = "opportunity";
            query.ColumnSet = new ColumnSet { AllColumns = true };
            query.Criteria = new FilterExpression();

            LinkEntity opportunity_account = new LinkEntity();
            opportunity_account.LinkFromEntityName = "opportunity";
            opportunity_account.LinkFromAttributeName = "customerid";
            opportunity_account.LinkToAttributeName = "accountid";
            opportunity_account.LinkToEntityName = "account";
            opportunity_account.JoinOperator = JoinOperator.Inner;


            opportunity_account.LinkCriteria = new FilterExpression();
            query.LinkEntities.Add(opportunity_account);
            query.LinkEntities[0].Columns.AddColumns(new string[] { "name" });
            query.LinkEntities[0].EntityAlias = "acc";

            ConditionExpression conditionExp = new ConditionExpression();
            conditionExp.AttributeName = "name";
            conditionExp.Operator = ConditionOperator.BeginsWith;
            conditionExp.Values.Add("王");
            opportunity_account.LinkCriteria.AddCondition(conditionExp);

            result = service.RetrieveMultiple(query);
            foreach (Entity tmp in result.Entities)
            {
                msg += string.Format("Id:{0},Name:{1},Owner:{2},AccountName:{3}<br/>", tmp.Id, tmp["name"], ((EntityReference)tmp["ownerid"]).Name, ((AliasedValue)tmp["acc.name"]).Value);
            }

            throw new InvalidPluginExecutionException(OperationStatus.Canceled, msg);

            #endregion

            #region 用FetchExpression查询当前系统中的所有客户数量
            FetchExpression fetchExp = new FetchExpression("account_countFetchExp");
            fetchExp.Query = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' aggregate='true'>
                                              <entity name='account'>
                                                <attribute name='accountid' alias='accountid_count' aggregate='count'/>
                                              </entity>
                                            </fetch>";
            result = service.RetrieveMultiple(fetchExp);
            throw new InvalidPluginExecutionException(string.Format("当前系统共包含{0}条客户记录。", ((AliasedValue)result.Entities[0]["accountid_count"]).Value));
            #endregion

            #region 用QueryExpression查询总数
            QueryExpression query = new QueryExpression();
            query.EntityName = "account";
            query.ColumnSet = new ColumnSet(new string[] { "accountid" });

            result = service.RetrieveMultiple(query);
            throw new InvalidPluginExecutionException(string.Format("当前系统共包含{0}条客户记录。", result.Entities.Count));
            #endregion

            #region 用fetchexpression查询总数
            FetchExpression fetchExp = new FetchExpression(@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                              <entity name='account'>
                                                <attribute name='accountid'/>
                                              </entity>
                                            </fetch>");
            result = service.RetrieveMultiple(fetchExp);
            throw new InvalidPluginExecutionException(string.Format("当前系统共包含{0}条客户记录。", result.Entities.Count));
            #endregion


            #region 用queryexpression实现分页查询
            int count = 0;
            int pageSize = 500;
            int pageNum = 1;

            QueryExpression query = new QueryExpression();
            query.EntityName = "account";
            query.ColumnSet = new ColumnSet(new string[] { "accountid" });

            query.PageInfo = new PagingInfo();
            query.PageInfo.Count = pageSize;
            query.PageInfo.PageNumber = pageNum;
            query.PageInfo.PagingCookie = null;

            while (true)
            {
                result = service.RetrieveMultiple(query);
                if (result.Entities != null)
                {
                    count += result.Entities.Count;
                }

                if (result.MoreRecords)
                {
                    query.PageInfo.PageNumber += 1;
                    query.PageInfo.PagingCookie = result.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            throw new InvalidPluginExecutionException(string.Format("当前系统共包含{0}条客户记录。", count));

            #endregion


            #region 用fetchexpression实现分页查询
            int pageSize = 500;
            int pageNum = 1;
            int count = 0;
            string pageCookie = string.Empty;


            string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                              <entity name='account'>
                                                <attribute name='accountid'/>
                                              </entity>
                                            </fetch>";
            FetchExpression fetchExp = new FetchExpression("accountFetchExp");
            while (true)
            {
                fetchXml = CreateFetchPagingXml(fetchXml, pageNum, pageSize, pageCookie);
                RetrieveMultipleRequest request = new RetrieveMultipleRequest();
                request.Query = new FetchExpression(fetchXml);
                result = ((RetrieveMultipleResponse)service.Execute(request)).EntityCollection;

                if (result.Entities != null)
                {
                    count += result.Entities.Count;
                }
                if (result.MoreRecords)
                {
                    pageNum += 1;
                }
                else
                {
                    break;
                }



            }
            throw new InvalidPluginExecutionException(string.Format("当前系统共包含{0}条客户记录。", count));

            #endregion


        }

        private string CreateFetchPagingXml(string fetchXml, int pageNum, int pageSize, string pageCookie)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(fetchXml);
            XmlAttributeCollection atts = doc.DocumentElement.Attributes;

            //每页的记录数
            XmlAttribute count = doc.CreateAttribute("count");
            count.Value = pageSize.ToString();
            atts.Append(count);

            //页号
            XmlAttribute page = doc.CreateAttribute("page");
            page.Value = pageNum.ToString();
            atts.Append(page);

            //paging-cookie
            if (!string.IsNullOrEmpty(pageCookie))
            {
                XmlAttribute paging_pageCookie = doc.CreateAttribute("paging-cookie");
                paging_pageCookie.Value = pageCookie;
                atts.Append(paging_pageCookie);
            }


            return doc.InnerXml.ToString();
        }
    }
}

 

代码分析

    进目前情况来看FetchExpression比QueryExpression强大,它在2011的版本中支持聚合查询。

你可能感兴趣的:(Dynamics CRM 2011 编程系列(18):插件中的Read操作)