.NET 用 SDK の事前バインド クラスを生成する

.NET プロジェクト用の事前バインド クラスの作成:

  • コードの可読性と保守性が向上します。
  • コンパイル時に型チェックが行われるため、エラーのリスクが軽減されます。
  • 開発者は IntelliSense を使用してテーブル、列、選択オプションを検出できるため、開発者の生産性が向上します。
  • OrganizationServiceContext クラスを提供します。これにより、LINQ を使用して Dataverse クエリを作成でき、その他の機能がデータを操作できます。

詳細情報:

Power Platform CLI pac modelbuilder ビルド コマンド を使用して、早期バインド コード クラスを生成します。 CrmSvcUtil.exe コード生成ツールを使用することもできますが、Dataverse の場合は pac modelbuilder build コマンドを使用することをお勧めします。 CrmSvcUtil.exe を使用して SDK for .NET の事前バインド クラスを生成する方法について学びます

多くの Power Platform CLI コマンドと同様、pac modelbuilder build には結果を制御するために使用できるパラメータが多数あります。 この記事では、ほとんどのユースケースで --settingsTemplateFile パラメータの使用から始めることをお勧めします。 このパラメータを使用して、他のすべての使用可能な設定を制御できる JSON ファイルを参照します。 こうすることで、パラメーターの長いリストを作成する必要がなくなり、プロジェクトに適した構成を更新して、必要なときにクラスを再生成できるようになります。

もちろん、必要に応じて、パラメーターを指定してビルド コマンドを使用することもできます。 パラメーターを使用する を参照します。

概要

準備:

  1. Power Platform CLI のインストール
  2. Power Platform CLI pac 認証コマンド を使って環境に接続します。

開始するには、以下の手順に従ってください:

  1. .NET プロジェクトで、 NuGet パッケージ参照を次のいずれかに追加します。

  2. model というフォルダーを作成します。

  3. model フォルダーに、次の設定を含む builderSettings.json ファイルを追加します。

    {
    "emitentityetc-comment": "Generate a constants structure that contains all of the field names by entity at the time of code generation.",
    "emitEntityETC": false,
    "emitfieldsclasses-comment": "Generate a constants structure that contains all of the field names by entity at the time of code generation.",
    "emitFieldsClasses": false,
    "emitvirtualattributes-comment": "When set, includes the Virtual Attributes of entities in the generated code.",
    "emitVirtualAttributes": false,
    "entitynamesfilter-comment": "Filters the list of entities are retrieved when reading data from Dataverse.",
    "entityNamesFilter": [
       "account",
       "contact"
    ],
    "entitytypesfolder-comment": "Folder name that contains entities.",
    "entityTypesFolder": "Entities",
    "generateGlobalOptionSets-comment": "Emit all Global OptionSets. Note: If an entity contains a reference to a global optionset, it is emitted even if this switch is not present.",
    "generateGlobalOptionSets": false,
    "generatesdkmessages-comment": "When set, emits Sdk message classes as part of code generation",
    "generateSdkMessages": true,
    "language-comment": "The language to use for the generated proxy code. This value can be either 'CS' or 'VB'. The default language is 'CS'.",
    "language": "CS",
    "logLevel-comment": "Log level. The default value is 'Off'.",
    "logLevel": "Off",
    "messagenamesfilter-comment": "Filters the list of messages that are retrieved when reading data from Dataverse.",
    "messageNamesFilter": [
       "searchautocomplete",
       "searchquery",
       "sample_*"
    ],
    "messagestypesfolder-comment": "Folder name that contains messages.",
    "messagesTypesFolder": "Messages",
    "namespace-comment": "The namespace for the generated code.",
    "namespace": "ExampleProject",
    "optionsetstypesfolder-comment": "Folder name that contains option sets.",
    "optionSetsTypesFolder": "OptionSets",
    "serviceContextName-comment": "The name for the generated service context. If a value is passed in, it's used for the Service Context. If not, no Service Context is generated.",
    "serviceContextName": "OrgContext",
    "suppressGeneratedCodeAttribute-comment": "When set, this suppress all generated objects being tagged with the code generation engine and version",
    "suppressGeneratedCodeAttribute": true,
    "suppressINotifyPattern-comment": "When enabled, doesn't write the INotify wrappers for properties and classes.",
    "suppressINotifyPattern": true
    }
    

    注意

    このファイルは、pac modelbuilder build--writesettingsTemplateFile パラメータ と使用して生成できるファイルの修正バージョンです。 パラメータの使用 でコメントなしでファイルを生成する方法についてご覧ください。

  4. 次のコマンドを使用して、 C:\projects\exampleproject\ がプロジェクトへのパスを表し、model が作成したフォルダーである builderSettings.json で定義された設定を使用して、接続環境用の事前バインド クラスを生成します。

    PS C:\projects\exampleproject\model> pac modelbuilder build -o . -stf .\builderSettings.json
    

    このコマンドには、これらのパラメーターを使います。

    exampleproject ディレクトリからこのコマンドを使用することもできます。

    PS C:\projects\exampleproject>pac modelbuilder build -o model -stf model\builderSettings.json
    

どのようなファイルが書き込まれるかを理解する

どちらのコマンドを使用しても、次のような出力が期待されます。

Connected to... Your Organization
Connected as you@yourorganization.onmicrosoft.com
Begin reading metadata from MetadataProviderService
      Begin Reading Metadata from Server
      Read 2 Entities - 00:00:00.732
      Read 0 Global OptionSets - 00:00:00.000
      Read 12 SDK Messages - 00:00:00.889
      Completed Reading Metadata from Server - 00:00:01.694
Completed reading metadata from MetadataProviderService - 00:00:01.697
Begin Writing Code Files
      Processing 2 Entities
      Wrote 2 Entities - 00:00:00.0625873
      Processing 12 Messages
      Wrote 3 Message(s). Skipped 9 Message(s) - 00:00:00.0091589
      Processing 0 Global OptionSets
      Wrote 0 Global OptionSets - 00:00:00.0000045
      Code written to C:\projects\exampleproject\model\Entities\account.cs.
      Code written to C:\projects\exampleproject\model\Entities\contact.cs.
      Code written to C:\projects\exampleproject\model\Messages\searchquery.cs.
      Code written to C:\projects\exampleproject\model\Messages\searchautocomplete.cs.
      Code written to C:\projects\exampleproject\model\OrgContext.cs.
      Code written to C:\projects\exampleproject\model\EntityOptionSetEnum.cs.
Completed Writing Code Files - 00:00:00.116
Generation Complete - 00:00:01.815
PS C:\projects\exampleproject\model>

出力を調べると、entityNamesFilter で指定されたテーブルのクラスと、messageNamesFilter で指定されたメッセージのみが生成されることに注意してください。 プロジェクトで使用するテーブル (エンティティ) とメッセージを指定する必要があります。 それ以外の場合は、すべてのテーブルとメッセージのクラスが生成されます。

messageNamesFilter の場合、これらの値にワイルドカード文字として * を使用できます。 これは、ソリューション内のメッセージが共通のカスタマイズ接頭辞を共有する場合に便利です。

設定ファイルで制御できる名前のフォルダーにファイル pac modelbuilder build を書き込みます。

  • エンティティ クラスは、entityTypesFolder 設定で指定されたフォルダーに書き込まれます。
  • メッセージ クラスは、messagesTypesFolder 設定で指定されたフォルダーに書き込まれます。
  • OrganizationServiceContext クラスは、serviceContextName 設定で指定された名前のファイルに書き込まれます。
  • すべてのクラスは、namespace 設定で設定した名前空間の一部です。

注意

メッセージ クラスを生成する場合は、serviceContextName 設定の名前を常に含める必要があります。 メッセージ クラスの生成時に serviceContextName を含める を参照してください

Visual Studio ではファイルとフォルダーが次のように表示されます。

 Visual Studio エクスプローラーの pac modelbuilder build コマンドからの出力例

これらのファイルをプロジェクトに書き込むと、事前バインド クラスを使用する準備が整いました。

変更したい場合は、model 以外の builderSettings.jsonフォルダ内のファイルを削除し、builderSettings.jsonの設定を変更して再生成してください。

パラメーターの使用

builderSettings.json 設定ファイルと --settingsTemplateFile パラメータを pac modelbuilder build で使用する必要はありません。 パラメーターを直接使用してコマンドを呼び出すことができます。 参照ドキュメントと例は、pac modelbuilder ビルド リファレンス ドキュメント にあります。

builderSettings.json 設定ファイルと --settingsTemplateFile パラメーターを使用している場合、コマンド ラインでパラメーターを使用して設定を上書きできます。

以下の例は、以下のパラメータを使用して はじめに セクション の例と同じ設定でファイルを生成する方法を示しています。

PS C:\>pac modelbuilder build `
   --outdirectory C:\projects\exampleproject\model `
   --entitynamesfilter 'account;contact' `
   --generatesdkmessages `
   --messagenamesfilter 'searchautocomplete;searchquery;sample_*' `
   --namespace ExampleProject `
   --serviceContextName OrgContext `
   --suppressGeneratedCodeAttribute `
   --suppressINotifyPattern `
   --writesettingsTemplateFile

デフォルトのオプションを使用するため、これにはすべての設定が含まれているわけではありません。 --writesettingsTemplateFile パラメータ を使用して builderSettings.json ファイルを生成する場合、この記事の はじめに セクション に例のコメントは含まれていません。 パラメータを使用した例ではmodel フォルダの次の builderSettings.json ファイルに記述します。

{
  "suppressINotifyPattern": true,
  "suppressGeneratedCodeAttribute": true,
  "language": "CS",
  "namespace": "ExampleProject",
  "serviceContextName": "OrgContext",
  "generateSdkMessages": true,
  "generateGlobalOptionSets": false,
  "emitFieldsClasses": false,
  "entityTypesFolder": "Entities",
  "messagesTypesFolder": "Messages",
  "optionSetsTypesFolder": "OptionSets",
  "entityNamesFilter": [
    "account",
    "contact"
  ],
  "messageNamesFilter": [
    "searchautocomplete",
    "searchquery",
    "sample_*"
  ],
  "emitEntityETC": false,
  "emitVirtualAttributes": false
}

メッセージ クラスの生成時に serviceContextName を含める を参照してください

メッセージ クラスを生成する場合は、OrganizationServiceContext クラスがコードで生成されるように、常に serviceContextName パラメータの名前を含める必要があります。 このクラスには、生成されたメッセージ クラスの使用を可能にする重要なプロパティが含まれています。 OrganizationServiceContext を含めない場合、生成されたメッセージ クラスを使用しようとすると次のエラーが発生します。

The formatter threw an exception while trying to deserialize the message: 
There was an error while trying to deserialize parameter http://schemas.microsoft.com/xrm/2011/Contracts/Services:request. 
The InnerException message was 'Error in line 1 position 700. Element 'http://schemas.microsoft.com/xrm/2011/Contracts/Services:request' contains data from a type that maps to the name 'http://schemas.microsoft.com/xrm/2011/new/:<your generated class name>'. 
The deserializer has no knowledge of any type that maps to this name. 
Consider changing the implementation of the ResolveName method on your DataContractResolver to return a non-null value for name '<your generated class name>' and namespace 'http://schemas.microsoft.com/xrm/2011/new/'.'.  
Please see InnerException for more details.

コミュニティ ツール

事前バインド ジェネレーター V2 はコミュニティによって作成された XrmToolBox プラグインで、事前バインド型を生成するためのユーザー インターフェイスやその他の多くの構成を提供します。

注意

コミュニティ ツールは Microsoft の製品ではなく、コミュニティ ツールに対するサポートは提供されません。 このツールに関するご質問は、その発行元にお問い合わせください。 詳細: XrmToolBox

Dynamics 365 Customer Engagement オンプレミスの場合

Power Platform CLI は、Dynamics 365 Customer Engagement (オンプレミス) では利用できません。 CrmSvcUtil.exe コード生成を使用して事前バインドクラスを生成する必要があります。 CrmSvcUtil.exe を使用して SDK for .NET の事前バインド クラスを生成する方法について学びます

遅延バインド および事前バインド プログラミング
サンプル: 事前バインド テーブル操作
開発者のツールとリソース
Dataverse 開発ツール
CrmSvcUtil.exe を使用して SDK for .NET の事前バインド クラスを生成する方法について学びます

注意

ドキュメントの言語設定についてお聞かせください。 簡単な調査を行います。 (この調査は英語です)

この調査には約 7 分かかります。 個人データは収集されません (プライバシー ステートメント)。