简体   繁体   English

ASP.NET 核心实体框架。 如何使用子查询编写异步查询?

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

This is code which I try to async.这是我尝试异步的代码。

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

I have alrady tried this, but it didn't work我已经尝试过这个,但它没有用

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

The main problem that I can't get subquery field CreatedDate .我无法获得子查询字段CreatedDate的主要问题。

The error message says:错误消息说:

'DateTime' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'DateTime' could be found (are you missing a using directive or an assembly reference?) “DateTime”不包含“GetAwaiter”的定义,并且找不到接受“DateTime”类型的第一个参数的可访问扩展方法“GetAwaiter”(您是否缺少 using 指令或程序集引用?)

The expression that is passed to Where is simply converted to SQL by EF, so there is no need to try and make it async.传递给Where的表达式被 EF 简单地转换为 SQL,因此无需尝试使其异步。

The ToListAsync method executes the query on the database asynchronously, so should be awaited: 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