次の方法で共有


単一データベース トランザクションでメッセージを実行する

ビジネス アプリケーションでは、システム内の複数のテーブル行の変更を調整して、すべてのデータ変更が成功するか、まったく変更しないようにすることが一般的な要件です。 データベースの用語では、どれか一つの操作が失敗したときにすべてのデータの変更をロール バックする機能を持つ単一のトランザクションで、複数の操作を実行することとして知られています。

ExecuteTransactionRequest メッセージ要求を使用して、1 つのデータベース トランザクションで 2 つ以上の要求を実行できます。 このメッセージを使用するには、トランザクションで実行される 2 つ以上の組織要求を Requests コレクションに設定します。 ReturnResponses コレクションで、実行されたメッセージ要求ごとに 1 つずつ、応答のコレクションを取得する場合は、trueResponses に設定します。 Requests コレクション内のメッセージ要求は、コレクションに表示される順序で実行されます。この場合、インデックス 0 の要素が最初に実行されます。 この同じ順序は、 Responses コレクションに保持されます。

いずれかの要求が失敗し、トランザクションがロールバックされた場合、トランザクション中に完了したデータの変更はすべて元に戻されます。 さらに、エラーの原因となった要求メッセージの要求コレクション内のインデックスを識別する ExecuteTransactionFault が返されます。

ExecuteMultipleRequestには、1 つ以上のExecuteTransactionRequest インスタンスが含まれている場合があります。 ExecuteTransactionRequest インスタンスには、ExecuteMultipleRequestまたはExecuteTransactionRequestが含まれていない場合があります。 ExecuteMultipleRequestの詳細については、「SDK for .NET を使用して複数の要求を実行する」を参照してください。

詳細情報: プラグインおよびワークフロー アクティビティでバッチ要求の種類を使用しない

Example

この例では、単一の Web メソッド呼び出しを使用して、1 つのデータベース トランザクションの一部としてコレクション内のすべてのメッセージ要求を実行します。 実行動作を変更するための設定も表示されます。

// Create an ExecuteTransactionRequest object.
var requestToCreateRecords = new ExecuteTransactionRequest()
{
// Create an empty organization request collection.
Requests = new OrganizationRequestCollection(),
ReturnResponses = true
};

// Create several (local, in memory) entities in a collection. 
var input = new EntityCollection()
{
EntityName = Account.EntityLogicalName,
Entities = {
            new Account { Name = "ExecuteTransaction Example Account 1" },
            new Account { Name = "ExecuteTransaction Example Account 2" },
            new Account { Name = "ExecuteTransaction Example Account 3" },
            new Account { Name = "ExecuteTransaction Example Account 4" },
            new Account { Name = "ExecuteTransaction Example Account 5" }
        }
};

// Add a CreateRequest for each entity to the request collection.
foreach (var entity in input.Entities)
{
CreateRequest createRequest = new CreateRequest { Target = entity };
requestToCreateRecords.Requests.Add(createRequest);
}

// Execute all the requests in the request collection using a single web method call.
try
{
var responseForCreateRecords =
    (ExecuteTransactionResponse)svc.Execute(requestToCreateRecords);

int i = 0;
// Display the results returned in the responses.
foreach (var responseItem in responseForCreateRecords.Responses)
{
    if (responseItem != null)
    Console.WriteLine("Created " + ((Account)requestToCreateRecords.Requests[i].Parameters["Target"]).Name
        + " with account id as " + responseItem.Results["id"].ToString());
    i++;
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
Console.WriteLine("Create request failed for the account{0} and the reason being: {1}",
    ((ExecuteTransactionFault)(ex.Detail)).FaultedRequestIndex + 1, ex.Detail.Message);
throw;
}

こちらも参照ください

.NET 用 SDK でメッセージを使用する
SDK for .NET を使用して複数の要求を実行する