用戶端與伺服器評估Client vs. Server Evaluation

Entity Framework Core 支援用戶端和它發送到資料庫的組件上所評估的查詢部分。Entity Framework Core supports parts of the query being evaluated on the client and parts of it being pushed to the database. 這是由資料庫提供者,以判斷查詢的哪些部分會評估在資料庫中。It is up to the database provider to determine which parts of the query will be evaluated in the database.

提示

您可以檢視這篇文章範例GitHub 上。You can view this article's sample on GitHub.

用戶端評估Client evaluation

在下列範例中的 helper 方法用來標準化從 SQL Server 資料庫所傳回的部落格的 Url。In the following example a helper method is used to standardize URLs for blogs that are returned from a SQL Server database. SQL Server 提供者會不有任何深入了解如何實作這個方法,因為它不可能將它轉譯為 SQL。Because the SQL Server provider has no insight into how this method is implemented, it is not possible to translate it into SQL. 評估查詢的所有其他部分會在資料庫中,但傳遞傳回URL透過這個方法不會對用戶端。All other aspects of the query are evaluated in the database, but passing the returned URL through this method is performed on the client.

var blogs = context.Blogs
    .OrderByDescending(blog => blog.Rating)
    .Select(blog => new
    {
        Id = blog.BlogId,
        Url = StandardizeUrl(blog.Url)
    })
    .ToList();
public static string StandardizeUrl(string url)
{
    url = url.ToLower();

    if (!url.StartsWith("http://"))
    {
        url = string.Concat("http://", url);
    }

    return url;
}

停用用戶端評估Disabling client evaluation

雖然用戶端評估會非常實用,在某些情況下可能會導致效能不佳。While client evaluation can be very useful, in some instances it can result in poor performance. 請考慮下列查詢中,現在在篩選中使用的 helper 方法。Consider the following query, where the helper method is now used in a filter. 這不能在資料庫中執行,因為所有資料提取到記憶體,然後篩選條件會套用至用戶端。Because this can't be performed in the database, all the data is pulled into memory and then the filter is applied on the client. 根據資料,以及多少資料都會被篩選掉的數量,這可能導致效能不佳。Depending on the amount of data, and how much of that data is filtered out, this could result in poor performance.

var blogs = context.Blogs
    .Where(blog => StandardizeUrl(blog.Url).Contains("dotnet"))
    .ToList();

根據預設,用戶端評估執行時 EF Core 時,會記錄警告。By default, EF Core will log a warning when client evaluation is performed. 請參閱記錄檢視記錄輸出的詳細資訊。See Logging for more information on viewing logging output. 用戶端評估擲回或不執行任何動作時,您可以變更此行為。You can change the behavior when client evaluation occurs to either throw or do nothing. 這是通常在設定為您的內容-選項時DbContext.OnConfiguring,或在Startup.cs如果您使用 ASP.NET Core。This is done when setting up the options for your context - typically in DbContext.OnConfiguring, or in Startup.cs if you are using ASP.NET Core.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder
        .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFQuerying;Trusted_Connection=True;")
        .ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
}