gpt4 book ai didi

C# 仅在需要时有条件地处理 Entity Framework DbContext

转载 作者:行者123 更新时间:2023-11-30 21:28:56 25 4
gpt4 key购买 nike

我正在努力使我的代码足够智能,以便仅在相关方法的当前执行生命周期内需要时才打开和处理 Entity Framework DBcontext。

基本上,如果将真实上下文传递到方法中,那么我不想处理它。但是,如果它只在相关方法的当前执行生命周期内需要,那么它将在 finally block 中处理

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 语句来做)吗?

最佳答案

你可以将逻辑封装在一个 helper disposable 中(这样你就可以利用 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;
}

关于C# 仅在需要时有条件地处理 Entity Framework DbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55856320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com