首页 > 解决方案 > ASP.NET 核心实体框架。如何使用子查询编写异步查询?

问题描述

这是我尝试异步的代码。

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 指令或程序集引用?)

标签: c#asp.net-coreentity-framework-core

解决方案


传递给的表达式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();
}

推荐阅读