EF4 context creation in one method
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 i开发者_运维知识库t 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 make InDb
require a generic type as well.
public TRet InDb<TRet>(Func<BodModelContainer, TRet> workingWithDb) {
TRet ret = default(TRet);
using (var dbContext = new BodModelContainer()) {
ret = workingWithDb(dbContext);
}
return ret;
}
public Member GetMemberById(int memberId) {
return InDb(dbContext => { return dbContext.Members.Find(new[] { memberId }); });
}
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.
public void InDb(Action<BodModelContainer> workingWithDb) {
using (var dbContext = new BodModelContainer()) {
workingWithDb(dbContext);
}
}
public Member GetMemberById(int memberId) {
Member member;
InDb(dbContext => { member = dbContext.Members.Find(new[] { memberId }); });
return member;
}
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 dbContext
used in InDb
I don't think it is very helpful.
精彩评论