4
\$\begingroup\$

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));
    }
}
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Some initial thoughts off the top of my head. I personally like immutability in my class data where possible. You have such available:

private readonly DataServiceContext context;

private readonly string collectionName;

public ServiceWrapper(Uri uri, string collection)
{
    context = new DataServiceContext(uri, DataServiceProtocolVersion.V3);
    collectionName = collection;
}

public string CollectionName { get { return collectionName; } }

Also, if you have LINQ available to you, you can simplify InvokeMethod():

public DataServiceQuery<T> InvokeMethod(string opName, params Tuple<string,object>[] args)
{
    return args.Aggregate(
        Context.CreateQuery<T>(opName),
        (current, pair) => current.AddQueryOption(pair.Item1, pair.Item2));
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.