簡體   English   中英

ASP.NET 核心實體框架。 如何使用子查詢編寫異步查詢?

[英]ASP.NET Core Entity Framework. How to write async query with subquery?

這是我嘗試異步的代碼。

public void MarkAsRead(Guid id)
{
   var notificationMessages = DbContext.NotificationMessages
        .Where(nm => !nm.IsRead && nm.CreatedDate <  DbContext.NotificationMessages.FirstOrDefault(x => x.Id == id).CreatedDate)
        .ToList();

        notificationMessages.ForEach(nm => nm.IsRead = true);
        DbContext.SaveChanges();
}

我已經嘗試過這個,但它沒有用

public async Task MarkAsRead(Guid id)
{
   var notificationMessages = await DbContext.NotificationMessages
        .Where( async nm => !nm.IsRead && nm.CreatedDate < await DbContext.NotificationMessages.FirstOrDefaultAsync(x => x.Id == id).Result.CreatedDate)
        .ToListAsync();

        notificationMessages.ForEach(nm => nm.IsRead = true);
        await DbContext.SaveChangesAsync();
}

我無法獲得子查詢字段CreatedDate的主要問題。

錯誤消息說:

“DateTime”不包含“GetAwaiter”的定義,並且找不到接受“DateTime”類型的第一個參數的可訪問擴展方法“GetAwaiter”(您是否缺少 using 指令或程序集引用?)

傳遞給Where的表達式被 EF 簡單地轉換為 SQL,因此無需嘗試使其異步。

ToListAsync方法在數據庫上異步執行查詢,所以應該等待:

public async Task MaskAsRead(Guid id)
{
   var notificationMessages = await DbContext.NotificationMessages
        .Where(nm => !nm.IsRead && nm.CreatedDate < DbContext.NotificationMessages.FirstOrDefault(x => x.Id == id).Result.CreatedDate)
        .ToListAsync();

    notificationMessages.ForEach(nm => nm.IsRead = true);
    await DbContext.SaveChangesAsync();
}

暫無
暫無

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

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