【问题标题】:ASP.NET Core Entity Framework. How to write async query with subquery?ASP.NET 核心实体框架。如何使用子查询编写异步查询?
【发布时间】:2020-05-22 19:37:29
【问题描述】:

这是我尝试异步的代码。

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”的定义,也没有 可访问的扩展方法“GetAwaiter”接受第一个参数 可以找到类型“DateTime”(您是否缺少 using 指令或 程序集参考?)

【问题讨论】:

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


    【解决方案1】:

    传递给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();
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-27
      • 1970-01-01
      • 2016-05-20
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 2021-12-13
      • 1970-01-01
      相关资源
      最近更新 更多