簡體   English   中英

C# 向用戶定義的 EF 查詢添加 NOLOCK

[英]C# Adding a NOLOCK to a user-defined EF query

我有以下用戶定義的查詢:

        var outerRingEntities = await Databases.OuterRing.Set<TOuterEntity>()
                                .AsNoTracking()
                                .Where(transformer.ShouldQueryItem)
                                .Where(x => LastSyncTime == null || x.ChangedDate > LastSyncTime)
                                .OrderBy(p => p.ChangedDate)
                                .Skip(index)
                                .Take(_pageSize)
                                .ToListAsync(cancellationToken);

目標是向該查詢添加“NOLOCK”。 為此,我研究並嘗試了很多不同的東西,但我仍然沒有解決方案:

嘗試1:我查看了以下鏈接: How to use SqlAzureExecutionStrategy and "Nolock"

我能夠添加SuspendableSqlAzureExecutionStrategy但唯一的問題是System.Runtime.Remoting.Messaging 我能夠在 .NET Framework 4.8 中找到此 dll,但消息傳遞仍然存在問題。 修改類后,我仍然收到以下錯誤:

"The configured execution strategy 'SqlServerRetryingExecutionStrategy' does not support user initiated transactions. Use the execution strategy returned by 'DbContext.Database.CreateExecutionStrategy()' to execute all the operations in the transaction as a retriable unit."

嘗試 2:我按照此博客中的說明進行操作: https ://dotnetdocs.ir/Post/38/implementing-nolock-in-entityframework-

按照博客上的說明,我修改了如下代碼:

    var outerRingEntities = await Databases.OuterRing.Set<TOuterEntity>()
                            .AsNoTracking()
                            .Where(transformer.ShouldQueryItem)
                            .Where(x => LastSyncTime == null || x.ChangedDate > LastSyncTime)
                            .OrderBy(p => p.ChangedDate)
                            .Skip(index)
                            .Take(_pageSize)
                            .ToListWithNoLockAsync(cancellationToken);

從這個查詢中,我們可以看到我正在使用一個擴展方法,這個方法是在提供的鏈接中定義的。

但是我仍然遇到與第一次嘗試相同的錯誤。

有沒有辦法讓我實現我的目標,以便我執行查詢以及向 EF 查詢添加一個 nolock。 請指教。

提前致謝。

  1. NOLOCK是邪惡的。 不要這樣做。 使用 READ COMMITTED SNAPSHOT 數據庫選項或設置的 SNAPSHOT 隔離級別。

  2. 如果您打開 DbContext 的數據庫連接,它將在 DbContext 生命周期內保持打開狀態。 因此,您可以啟動 ReadUncommited事務,或更改 TSQL 中的事務隔離級別,后續查詢將運行臟讀。

暫無
暫無

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

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