繁体   English   中英

C#仅在需要时有条件地处置实体框架DbContext

[英]C# Conditionally disposing of Entity Framework DbContext only when needed

我试图使我的代码足够智能,以便仅在有问题的方法的当前执行生命周期内仅需要打开和处置Entity Framework DBcontext时才可以。

基本上,如果真实的语境被传递到方法,然后我不想处置。 但是,如果仅在所讨论方法的当前执行生命周期中需要它,它将被放置在finally块中

public int UpSertCompanyStockInfo( Guid companyId, string companyName, float stockPrice, float peRatio, CommunicationEngineDatabase context)
{
    bool isContextOnlyCreatedForCurrentMethodExecutionRun = false;
    if (context == null)
    {
        isContextOnlyCreatedForCurrentMethodExecutionRun = true;
        context = new CommunicationEngineDatabase();
    }
    try
    {
        CompanyStockInfo companyStockInfo = new CompanyStockInfo();
        companyStockInfo.CompanyName = companyName;
        companyStockInfo.StockPrice = stockPrice;

        context.CompanyStockInfoTable.Add(companyStockInfo);
        context.SaveChanges();
    }
    catch (Exception _ex)
    {

    }
    finally
    {
        if (isContextOnlyCreatedForCurrentMethodExecutionRun == true && context != null)
        {
            ((IDisposable)context).Dispose();
        }

    }
    return 0;

}

问题是,我认为上述代码在代码行方面太多了。 有人可以告诉我如何缩短它(甚至可以通过using语句来做到)吗?

您可以将逻辑封装在助手类中(这样就可以使用using )类(甚至struct ),如下所示:

class DbContextScope : IDisposable
{
    public static DbContextScope Open<TContext>(ref TContext context) where TContext : DbContext, new()
        => context != null ? NullScope : new DbContextScope(context = new TContext());
    static readonly DbContextScope NullScope = new DbContextScope(null);
    private DbContextScope(DbContext context) => this.context = context;
    readonly DbContext context;
    public void Dispose() => context?.Dispose();
}

样本的用法是:

public int UpSertCompanyStockInfo( Guid companyId, string companyName, float stockPrice, float peRatio, CommunicationEngineDatabase context)
{
    using (DbContextScope.Open(ref context))
    {
        CompanyStockInfo companyStockInfo = new CompanyStockInfo();
        companyStockInfo.CompanyName = companyName;
        companyStockInfo.StockPrice = stockPrice;

        context.CompanyStockInfoTable.Add(companyStockInfo);
        context.SaveChanges();
    }
    return 0;    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM