c# - 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 指令或程序集引用?)
解决方案
传递给的表达式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();
}
推荐阅读
- javascript - 将 dataURI 转换为文件以通过 REST 上传不起作用,但正常的文件字段上传工作正常
- r - R 重新定义 base::mean() 函数以包含 is.finite() 功能
- c# - 我在 .NET fiddle 中使用 void 函数时遇到问题
- python - Get_Actions EOSFLARE API
- java - swagger-ui.html 在 Vaadin + Spring 应用程序中显示空白页面
- python - 尝试将 Python UTF-8 标准输出重定向到 Windows 上的文件时发生错误
- html - 悬停图像时图像文本改变颜色
- javascript - 防止同时单击具有相同类的按钮
- visual-studio-code - 如何更改 VSCode Jupyter Notebook 的单元格背景颜色?
- node.js - 在 try 块中返回未定义的函数