[英]How to Create Entity Framework DBContext Extension Method?
I want to write an extension method on dbContextOptionsBuilder
which turns on client-side evaluation warning.我想在
dbContextOptionsBuilder
上编写一个扩展方法,它会打开客户端评估警告。 All our 10 db contexts will have this extension, and this way, we can toggle all with single boolean variable.我们所有的 10 db 上下文都将具有此扩展名,这样,我们可以使用单个 boolean 变量来切换所有上下文。
We are preparing to eventually migrate to Entity Framework Core 3, which does not allow client side evaluation.我们正准备最终迁移到不允许客户端评估的 Entity Framework Core 3。
Would this be an proper extension method?这会是一个合适的扩展方法吗?
public static DbContextOptionsBuilder ToggleClientEvaluationWarning(this DbContextOptionsBuilder dbContextOptionsBuilder, bool toggleSwitch = false)
{
if (toggleSwitch)
{
return dbContextOptionsBuilder.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
}
else
{
return dbContextOptionsBuilder;
}
}
https://devblogs.microsoft.com/dotnet/announcing-ef-core-3-0-and-ef-6-3-general-availability/ https://devblogs.microsoft.com/dotnet/announcing-ef-core-3-0-and-ef-6-3-general-availability/
How to write an extension method in DbContext class? 如何在 DbContext class 中编写扩展方法?
Your code is a possible solution that could be simplified.您的代码是可以简化的可能解决方案。
But before you should respect possible performance issues if you would perform more than enable client warnings.但是,如果您执行的不仅仅是启用客户端警告,那么在您应该尊重可能的性能问题之前。
1st simplification:第一个简化:
public static DbContextOptionsBuilder ToggleClientEvaluationWarning(this DbContextOptionsBuilder dbContextOptionsBuilder, bool toggleSwitch = false)
{
if (toggleSwitch)
{
return dbContextOptionsBuilder.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
}
return dbContextOptionsBuilder;
}
2nd round:第二轮:
public static DbContextOptionsBuilder ToggleClientEvaluationWarning(this DbContextOptionsBuilder dbContextOptionsBuilder, bool toggleSwitch = false)
{
return toggleSwitch
? dbContextOptionsBuilder.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning))
: dbContextOptionsBuilder;
}
Here is an additional blog post for further information. 这是一篇额外的博客文章以获取更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.