public virtual T Update(T entity, MyDbContext dbExternal = null)
{
bool isUseExternal = false;
MyDbContext db = null;
if (dbExternal == null)
{
db = new MyDbContext();
}else
{
db = dbExternal;
isUseExternal = true;
}
try{
//user db
}finally
{
if(!isUseExternal)db.Dispose();
}
}
解释一下意图, 该方法允许传入一个外部的dbcontext对象, 如果有传入那么用外部的dbcontext否则就new一个, 最后如果是方法内部自己new的dbcontext那么需要调用dispose, 否则不许调用
能改进吗?
感觉这样写太麻烦
public virtual T Update(T entity, MyDbContext dbExternal = null)
{
bool isUseExternal = dbExternal==NULL ?TRUE:FALSE;
MyDbContext db = dbExternal??new MyDbContext();
try{
//user db
}finally
{
if(!isUseExternal)db.Dispose();
}
}
有办法用上using(){}吗?
再简化一点成了
public virtual T Update(T entity, MyDbContext dbExternal = null)
{
var db = dbExternal??new MyDbContext;
try{
//use db
}finally
{
if(dbExternal==null )db.Dispose();
}
}
改成这样先用着了, 以后再考虑用aop重构了
thanks