I have many methods like this:
public IEnumerable<Director> GetAllDirectors()
{
using (var dbContext = new BodModelContainer())
{
return dbContext.Members.OfType<Director>().ToList();
}
}
..or this..
public Member GetMemberById(int memberId)
{
using(var dbContext = new BodModelContainer())
{
return dbContext.Members.Find(new[] {memberId});
}
}
or that:
public SomeType GetOrDoSomethingWithDbBySomethingElse(T1 t1var, T2, T2 var, ...)
{
using(var dbContext = new BodModelContainer())
{
return dbContext.SomeType.DoSomething();
}
}
So I wanna reorganize all of these methods something like:
// create db context here
public void InDb(Func<BodModelContainer, out SomeGenericType???> workingWithDb)
{
using(var dbContext = new BodModelContainer())
{
workingWithDb(dbContext);
}
}
// using it like
public Member GetMemberById(int memberId)
{
InDb((dbContext) =>
{
return dbContext.Members.Find(new[] { memberId });
});
}
Question: How to make such generic InDb method, what is SomeGenericType???
The actual problem it looks like you’re describing is the fact that you can’t figure out how to set the return type of the
Func<>. To be able to make this generic you’ll need to makeInDbrequire a generic type as well.Should work (all the code here is untested), or using anonymous methods you could have a local variable and make .Net do all the nasty work.
Of course, this all being said, I don’t know if this level of redirection/abstraction is useful – you’re making it slightly more complicated with little perceptible gain (if any). Unless there is a lot of work setting up and tearing down the
dbContextused inInDbI don’t think it is very helpful.