簡體   English   中英

如何創建實體框架 DBContext 擴展方法?

[英]How to Create Entity Framework DBContext Extension Method?

我想在dbContextOptionsBuilder上編寫一個擴展方法,它會打開客戶端評估警告。 我們所有的 10 db 上下文都將具有此擴展名,這樣,我們可以使用單個 boolean 變量來切換所有上下文。

我們正准備最終遷移到不允許客戶端評估的 Entity Framework Core 3。

這會是一個合適的擴展方法嗎?

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/

如何在 DbContext class 中編寫擴展方法?

您的代碼是可以簡化的可能解決方案。
但是,如果您執行的不僅僅是啟用客戶端警告,那么在您應該尊重可能的性能問題之前。

第一個簡化:

public static DbContextOptionsBuilder ToggleClientEvaluationWarning(this DbContextOptionsBuilder dbContextOptionsBuilder, bool toggleSwitch = false)
{
    if (toggleSwitch)
    {
        return dbContextOptionsBuilder.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
    }

    return dbContextOptionsBuilder;
}

第二輪:

public static DbContextOptionsBuilder ToggleClientEvaluationWarning(this DbContextOptionsBuilder dbContextOptionsBuilder, bool toggleSwitch = false)
{
    return toggleSwitch
        ? dbContextOptionsBuilder.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning))
        : dbContextOptionsBuilder;
}

這是一篇額外的博客文章以獲取更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM