Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing database context to static methods

I have a class with some static lists. For demonstrative purposes I'll only show two:

public class Foo
{
    public static readonly List<long> FirstList(EfEntities dbContext)
    {
        return dbContext.SomeTable.Where(x => x == 1).ToList();
    }

    public static readonly List<long> SecondList(EfEntities dbContext)
    {
        return dbContext.SomeTable.Where(x => x == 2).ToList();
    }
}

I'm not a big fan of passing my database context to each and every static method. Do you have any suggestions on different approaches?

like image 592
Johan Avatar asked Mar 23 '23 08:03

Johan


2 Answers

A good idea in that case (of course if usage of static methods is justified by the architecture, but this seems to be out of scope of this question) might be creating your static methods as extension methods:

public static class EfEntitiesExtensions
{
    public static readonly List<long> FirstList(this EfEntities dbContext)
    {
        return dbContext.SomeTable.Where(x => x == 1).ToList();
    }

    public static readonly List<long> SecondList(this EfEntities dbContext)
    {
        return dbContext.SomeTable.Where(x => x == 2).ToList();
    }
}

After that you can call them like this:

...
EfEntities dbContext = new EfEntities();
List<long> firstList = dbContext.FirstList();
like image 150
tpeczek Avatar answered Apr 06 '23 20:04

tpeczek


I personally don't like the idea of passing a dbContext object as a parameter. You could separate the data layer completely and store it in another class.

public class DataAccess {
   private EFEntities _dbContext { get; set; }

   public EfEntities GetDbContext() {
        if (_dbContext != null) {
             return _dbContext;
        } else {
            _dbContext = new EFEntities(.....);
            return _dbContext;
        }
   }
}

Then you can reference the DataAccess class which contains the context you need rather than passing it as a parameter each time.

like image 35
Darren Avatar answered Apr 06 '23 19:04

Darren