Search code examples
c#sqldatacontext

Using DataContext in every function


I have a class that handles all database operations. I've read that it's better to use multiple DataContext instances for different read/write/update/delete operations as opposed to one DataContext instance that lives a long time.

That means every function that does read/write/update/delete on the DB needs to do this:

    public int GetSomeID(string name)
    {
        using (XXDataContext context = new XXDataContext(connStr))
        {
            ...
        }
    }

    public int GetAnotherID(string name)
    {
        using (XXDataContext context = new XXDataContext(connStr))
        {
            ...
        }
    }

    public void WriteSomething(string text)
    {
        using (XXDataContext context = new XXDataContext(connStr))
        {
            ...
        }
    }

opposed to having this using() only in constructor and having the context as a private member variable available to every function call.

With keeping the functionality of creating a new DataContext with every function call, is it possible to move this using() somewhere else so not every single function has to have this line in it?


Solution

  • You can use a method like this to avoid re-writing the using code:

    private static void WithContext(Action<XXDataContext> action)
    {
        using(XXDataContext context = new XXDataContext(connStr))
            action(context);
    }    
    private static T WithContext<T>(Func<XXDataContext, T> function)
    {
        using(XXDataContext context = new XXDataContext(connStr))
            return function(context);
    }
    

    This allows you to write:

    public int GetSomeID(string name)
    {
        WithContext(context => 
            {
                //TODO use context
            });
    }
    

    If that helps you.