我有这个方法
public static List<_Account> Get(_User user, string name = null, SearchType sName = SearchType.Equals)
{
using (Context context = new Context())
{
IQueryable<_Account> query = context.Accounts;
if (!string.IsNullOrEmpty(name) && sName == SearchType.Equals)
query = query.Where(r => r.Name.Equals(name));
if (!string.IsNullOrEmpty(name) && sName == SearchType.StartsWith)
query = query.Where(r => r.Name.StartsWith(name));
if (!string.IsNullOrEmpty(name) && sName == SearchType.Contains)
query = query.Where(r => r.Name.Contains(name));
return query.ToList();
}
}
这有效,但是当我从另一个已经定义了上下文的方法调用此方法时,我想重用该上下文。我会添加一个可选参数
public static List<_Account> Get(..., Context ctx = null) {...
如果ctx != null
我想要将该上下文用于而不是放在最后。另外,我希望在使用中创建的上下文被使用并放置在方法的末尾。
答案 0 :(得分:2)
您可以将null放入using块中,以便以下工作:
public static List<_Account> Get(_User user, Context contextProvided = null, string name = null, SearchType sName = SearchType.Equals)
{
using (Context contextInner = (contextProvided == null ? new Context() : null)) //magic here
{
Context context = contextProvided ?? contextInner; //magic here
IQueryable<_Account> query = context.Accounts;
if (!string.IsNullOrEmpty(name) && sName == SearchType.Equals)
query = query.Where(r => r.Name.Equals(name));
if (!string.IsNullOrEmpty(name) && sName == SearchType.StartsWith)
query = query.Where(r => r.Name.StartsWith(name));
if (!string.IsNullOrEmpty(name) && sName == SearchType.Contains)
query = query.Where(r => r.Name.Contains(name));
return query.ToList();
}
}
另一个好方法是将方法(查询)的内容提取到辅助方法中。然后,您可以将now outer方法复制到两个重载中。一个重载创建一个上下文,其中一个将其作为参数。
如果这种模式发生很多,你可以通过创建自定义IDisposable
派生类来实现这样的目标:
public static List<_Account> Get(_User user, Context contextProvided = null, ...)
{
using (var contextProvider = new ContextProvider(contextProvided))
{
Context context = contextProvider.EffectiveContext;
//...
}
}