System.NullReferenceException 在 Dynamics CRM 控制台应用程序中执行 FetchXML 时

System.NullReferenceException When Executing FetchXML in Dynamics CRM Console App

我们使用的是 Dynamics CRM 2016 On-Premise。我正在尝试从 Dynamics CRM 控制台应用程序执行 FetchXML。

我可以成功连接到我们的 CRM。

我已经成功测试了 FetchXML 并使用 XrmToolbox (https://www.xrmtoolbox.com/plugins/MscrmTools.FetchXmlTester) 返回了结果

但我一直收到 System.NullReferenceException 在尝试执行 FetchXML 的 RetrieveMultiple 步骤中未将对象引用设置为对象的实例...非常感谢任何建议。 这是我的代码:

class Program
{

    private const string GetSampleAccounts = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
      <entity name='account'>
        <attribute name='name' />
        <attribute name='new_myfield' />
        <attribute name='accountid' />
        <order attribute='name' descending='false' />
        <filter type='and'>
          <condition attribute='new_myfield' operator='like' value='%888' />
        </filter>
      </entity>
    </fetch>";
    static void Main(string[] args)
    {
        try
        {
            var connectionString = @"AuthType=IFD;
            Username=rri\myname;
            Integrated Security=true;
            Url=https://Mmycrm.com;
            LoginPrompt=Auto";
            CrmServiceClient conn = new CrmServiceClient(connectionString);
            Console.WriteLine("Connection Successful!...");

            IOrganizationService service;
            service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

            DataCollection<Entity> result = service.RetrieveMultiple(new FetchExpression(string.Format(GetSampleAccounts))).Entities; //GET ERROR HERE

            if (result != null && result.Count == 1)
            {
                foreach (Entity account in result)
                {                      
                    Console.WriteLine(account.Attributes["name"];
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.ReadLine();
        }

        Console.ReadKey();
    }

试试这个:

string connectionString = @"AuthType=AD;Url=https://Mmycrm.com";

using (var service = new CrmServiceClient(connectionString))
{
    foreach (Entity account in service.RetrieveMultiple(new FetchExpression(GetSampleAccounts))
        .Entities)
    {
        Console.WriteLine(account.Attributes["name"]);
    }
}

另见 Use connection strings in XRM tooling to connect to Dynamics 365 Customer Engagement (on-premises) - MS Docs