[英]EF core 6 result doesn't match the database
我執行一個查詢,但我並不總是得到相同的結果。
我用斷點一步一步地執行了下面的代碼片段。 此代碼的用例是等到某個進程不再忙,然后再繼續執行。
string slug = "abc";
Entity entity = await _resource.GetQueryable()
.Where(x => x.Slug == slug)
.FirstOrDefaultAsync();
// entity.IsBusy is true
int retries = 0;
while(entity.IsBusy)
{
if (retries > 10)
{
throw new SyncIsBusyException();
}
retries++;
// Now I manually execute an SQL query on the database.
// update Entities set IsBusy = 'false'
Thread.Sleep(3000);
entity = await _resource.GetQueryable()
.Where(x => x.Slug == slug)
.FirstOrDefaultAsync();
// entity.IsBusy is still true (not in the DB)
string test = await _resource.GetQueryable()
.Where(x => x.Slug == slug)
.Select(x => x.IsBusy)
.FirstOrDefaultAsync();
// test is false (which is correct)
// test if creating a new variable changes things
var test1 = await _resource.GetQueryable()
.Where(x => x.Slug == slug)
.FirstOrDefaultAsync();
// test1.IsBusy is true (which is again incorrect)
}
資源:
public virtual IQueryable<TEntity> GetQueryable()
{
var queryable = _dbContext.Set<TEntity>().AsQueryable();
return queryable;
}
它看起來像某種緩存,但我沒有任何設置。 我還可以看到正在控制台中執行的 SQL 查詢。 當我在數據庫上手動執行這個生成的 SQL 查詢時,我得到了正確的預期結果(IsBusy false)。 我可以通過添加bool isBusy = entity.IsBusy;
來修復這個錯誤。 上面的while
然后使用那個。 但我仍然想知道這里的根本問題。
Slug
是您實體的主鍵嗎?
更改跟蹤器將通過其主鍵緩存實體,除非您清除本地緩存( dbContext.ChangeTracker.Clear()
)或首先使用.AsNoTracking()
查詢它。
后者確實阻止了對實體的更新。
Select
查詢投影實體的子集,以便針對存儲執行查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.