-
Notifications
You must be signed in to change notification settings - Fork 4
Batch
Batch operations can help improve performance by grouping several CRUD operations into a single request. This is very useful when working with ad hoc collections of homogeneous entities. A single batch may contain any combination of reads, inserts, updates and deletes.
The following example reads 3 contacts in a single request and outputs their names.
var client = new SDataClient("http://example.com/sdata/slx/dynamic/-/")
{
UserName = "admin",
Password = "password"
};
var batch = client.CreateBatch<Contact>();
batch.GetAll("CDEMOA000001", "CDEMOA000002", "CDEMOA000003");
var contacts = await batch.CommitAsync();
Console.WriteLine(contacts[0].FullName);
Console.WriteLine(contacts[1].FullName);
Console.WriteLine(contacts[2].FullName);
Note: The same can be accomplished using a normal collection request with an
in
filter expression.
The fetched resources can then be mutated and updated in another batch operation. Batch objects are single use, so a new one must be created after each commit. The following example changes the status of each contact returned in the previous example and updates them in a single request.
foreach (var contact in contacts)
{
contact.Status = "Inactive";
}
var batch = client.CreateBatch<Contact>();
batch.PutAll(contacts);
await batch.CommitAsync();
Each of the batch CRUD methods returns a Lazy<T>
object that's activated once the batch has been committed. This provides an alternative way to access the result resource for each individual item.
Note:
Lazy<T>
was introduced in .NET 4.0 so the batch methods in the .NET 2.0 and 3.5 versions of this library return void instead.
The following example fetches the same three contacts and accesses each of their names using the lazy placeholders.
var batch = client.CreateBatch<Contact>();
var lazy1 = batch.Get("CDEMOA000001");
var lazy2 = batch.Get("CDEMOA000002");
var lazy3 = batch.Get("CDEMOA000003");
await batch.CommitAsync();
Console.WriteLine(lazy1.Value.FullName);
Console.WriteLine(lazy2.Value.FullName);
Console.WriteLine(lazy3.Value.FullName);
Touching the Value
property on the lazy placeholder before the batch has been commit will cause an exception.
More information on batch operations can be found in section 13 of the SData specification.