QueryExpression のサンプル コード

C# で QueryExpression を使用するには、OutputQueryExpression を適応させて、この記事の 静的メソッドを使用できます。

ヒント

ページ内のデータを取得するためのサンプル コードについては、 ページング Cookie の例 を参照してください。

次の OutputQueryExpression 静的メソッドを使用して、コンソール アプリケーションで QueryExpression クエリをテストできます。

OutputQueryExpression メソッドは、 QueryExpression クラス と IOrganizationService.RetrieveMultiple メソッド を使用して、要求されたデータを含む EntityCollection を返す方法を示しています。

この OutputQueryExpression メソッドは ConsoleTables NuGet パッケージ に依存しており、列を含むすべての LinkEntity インスタンスで EntityAlias を指定する必要があります。

/// <summary>
/// Renders the output of a query in a table for a console application
/// </summary>
/// <param name="service">The authenticated IOrganizationService instance to use.</param>
/// <param name="query">The query to use</param>
/// <exception cref="Exception">
/// OutputQueryExpression requires all LinkEntity instances that contain columns specify an EntityAlias property.
/// </exception>
static void OutputQueryExpression(IOrganizationService service, QueryExpression query)
{
    //Retrieve the data
    EntityCollection entityCollection = service.RetrieveMultiple(query: query);

    //Get column names from the query
    var columns = GetQueryExpressionColumns(query);

    // Create the table using https://www.nuget.org/packages/ConsoleTables/2.5.0
    var table = new ConsoleTables.ConsoleTable(columns.ToArray());

    // Add the rows of the table
    entityCollection.Entities.ToList().ForEach(entity =>
    {
        table.Rows.Add(GetRowValues(columns, entity).ToArray());
    });

    // Write the table to the console
    table.Write();

    // Get a list of column names from the query
    List<string> GetQueryExpressionColumns(QueryExpression query)
    {
        List<string> columns = new();

        columns.AddRange(GetColumns(query.ColumnSet));

        foreach (LinkEntity linkEntity in query.LinkEntities)
        {
            columns.AddRange(GetLinkEntityColumns(linkEntity));
        }

        return columns;
    }

    // Get column names from any linked tables
    List<string> GetLinkEntityColumns(LinkEntity linkEntity)
    {
        if (string.IsNullOrWhiteSpace(linkEntity.EntityAlias))
        {
            if (linkEntity.Columns.Columns.Count != 0)
            {
                string message = "OutputQueryExpressionRequest requires all ";
                message += "LinkEntity instances that contain columns ";
                message += "specify an EntityAlias property.";

                throw new Exception(message);
            }
        }

        List<string> columns = new();

        columns.AddRange(GetColumns(linkEntity.Columns, linkEntity.EntityAlias));

        foreach (LinkEntity le in linkEntity.LinkEntities)
        {
            columns.AddRange(GetColumns(le.Columns, le.EntityAlias));
        }
        return columns;
    }

    // Get columns from a columnset
    List<string> GetColumns(ColumnSet columnset, string alias = null)
    {
        List<string> columns = new();

        foreach (string column in columnset.Columns)
        {
            columns.Add(string.IsNullOrWhiteSpace(alias) ? column : $"{alias}.{column}");
        }

        foreach (XrmAttributeExpression item in columnset.AttributeExpressions)
        {
            columns.Add(item.Alias ?? item.AttributeName);
        }

        return columns;
    }

    // Get the values of a row as strings
    List<string> GetRowValues(List<string> columns, Entity entity)
    {
        List<string> values = new();
        columns.ForEach(column =>
        {
            if (entity.Attributes.ContainsKey(column))
            {
                // Use the formatted value if it available
                if (entity.FormattedValues.ContainsKey(column))
                {
                    values.Add($"{entity.FormattedValues[column]}");
                }
                else
                {
                    // When an alias is used, the Aliased value must be converted
                    if (entity.Attributes[column] is AliasedValue aliasedValue)
                    {
                        // When an EntityReference doesn't have a Name, show the Id
                        if (aliasedValue.Value is EntityReference lookup &&
                        string.IsNullOrWhiteSpace(lookup.Name))
                        {
                            values.Add($"{lookup.Id:B}");
                        }
                        else
                        {
                            values.Add($"{aliasedValue.Value}");
                        }
                    }
                    else
                    {
                        // Use the simple attribute value
                        values.Add($"{entity.Attributes[column]}");
                    }
                }
            }
            // Null values are not in the Attributes collection
            else
            {
                values.Add("NULL");
            }

        });
        return values;
    }
}

Update SDK for .NET クイック スタート サンプル

次の手順で、クイック スタート: SDK for .NETリクエスト (C#) の実行 サンプルを調整して、クエリをテストできます。

  1. ConsoleTables NuGet パッケージのインストール

  2. 次の using ステートメントを program.cs ファイルの上位に追加します

    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    using System.Text;
    using System.Xml.Linq;
    
  3. OutputQueryExpression のメソッドをコピーして、Main の方法の下に貼り付けてください。

  4. Main メソッドを編集してクエリを設定し、OutputQueryExpression メソッドを使用します。

        static void Main(string[] args)
        {
            using (ServiceClient serviceClient = new(connectionString))
            {
                if (serviceClient.IsReady)
                {
                    //WhoAmIResponse response = 
                    //    (WhoAmIResponse)serviceClient.Execute(new WhoAmIRequest());
    
                    //Console.WriteLine("User ID is {0}.", response.UserId);
    
                     QueryExpression query = new("account")
                     {
                        TopCount = 5,
                        ColumnSet = new ColumnSet(
                           "accountclassificationcode", 
                           "createdby", 
                           "createdon", 
                           "name")
                     };
    
                    OutputQueryExpression(serviceClient, query);
                }
                else
                {
                    Console.WriteLine(
                        "A web service connection was not established.");
                }
            }
    
            // Pause the console so it does not close.
            Console.WriteLine("Press the <Enter> key to exit.");
            Console.ReadLine();
        }
    

アプリケーション コードでの接続文字列の使用については、次の重要な情報をお読みください。

重要

Microsoft では、利用可能な最も安全な認証フローを使用することをお勧めします。 この記事で説明する認証フローは、アプリケーションに対する非常に高い信頼を必要とし、他のフローには存在しないリスクを伴います。 このフローは、マネージド ID など、他のより安全なフローが実行できない場合にのみ使用してください。

OutputQueryExpression メソッドを使用してプログラムを実行すると、出力は次のようになります:

 ---------------------------------------------------------------------------------------------------------
 | accountclassificationcode | createdby          | createdon          | name                             |
 ---------------------------------------------------------------------------------------------------------
 | Default Value             | FirstName LastName | 3/25/2023 10:42 AM | Litware, Inc. (sample)           |
 ---------------------------------------------------------------------------------------------------------
 | Default Value             | FirstName LastName | 3/25/2023 10:42 AM | Adventure Works (sample)         |
 ---------------------------------------------------------------------------------------------------------
 | Default Value             | FirstName LastName | 3/25/2023 10:42 AM | Fabrikam, Inc. (sample)          |
 ---------------------------------------------------------------------------------------------------------
 | Default Value             | FirstName LastName | 3/25/2023 10:42 AM | Blue Yonder Airlines (sample)    |
 ---------------------------------------------------------------------------------------------------------
 | Default Value             | FirstName LastName | 3/25/2023 10:42 AM | City Power & Light (sample)      |
 ---------------------------------------------------------------------------------------------------------

QueryExpression を使用したデータのクエリ
サンプル: QueryExpression クラスを使用した複数取得
サンプル: ページング Cookie を使用した QueryExpression の使用