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?
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With