The class is responsible for wrapping requests to a WCF Data Service, which tidies up calling code. Transactions are implicitly supported. It should efficiently send just updates to the services (only changed values). The next step is to modify it and allow named properties to be queried, rather than all fields.
Please review this.
using System;
using System.Data.EntityClient;
using System.Data.Objects;
using System.Data.Services.Client;
using System.Data.Services.Common;
using System.Threading.Tasks;
internal class ServiceWrapper<T>
{
private DataServiceContext context;
public ServiceWrapper(Uri uri, string collection)
{
context = new DataServiceContext(uri, DataServiceProtocolVersion.V3);
CollectionName = collection;
}
public string CollectionName { get; private set; }
public DataServiceContext Context
{
get { return context; }
}
public DataServiceQuery<T> QueryAll
{
get { return Context.CreateQuery<T>(CollectionName); }
}
public DataServiceQuery<T> InvokeMethod(string opName, params Tuple<string,object>[] args)
{
DataServiceQuery<T> query = Context.CreateQuery<T>(opName);
foreach (Tuple<string, object> pair in args)
{
query = query.AddQueryOption(pair.Item1, pair.Item2);
}
return query;
}
public void Add(T entity)
{
context.AddObject(CollectionName, entity);
}
public void Update(T entity)
{
context.AttachTo(CollectionName, entity);
context.UpdateObject(entity);
}
public void Delete(T entity)
{
context.AttachTo(CollectionName, entity);
context.DeleteObject(entity);
}
public async Task CommitAsync()
{
await Task.Run(() => context.SaveChanges(SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch));
}
}