c# - EF Core 不会两次从数据库中获取数据
问题描述
我使用 .NET Core 3.1 和 EF Core 3.1。我编写了一个方法来从 SQL Server 数据库中获取一行Id
。
我的问题是,当我第一次获取数据时,它是可以的,但是当我再次获取相同的数据时,第二次,数据没有正确获取并返回a
可变数据而不是数据库行(请参阅我的代码中的注释)。
public async Task<AcademyStudent> GetItemAsync(Guid id)
{
var a = await _context.AcademiesStudents
.SingleOrDefaultAsync(x => x.Id == id);
// the value of property a.Mobile is "09123456789"
// change Mobile property with other data
a.Mobile = "0000";
// fetch again data from db with same query
var b = await _context.AcademiesStudents
.SingleOrDefaultAsync(x => x.Id == id);
// but the value of b.Mobile is not "09123456789" but also is "0000". why!??? :(
return b;
}
我的问题在哪里?以及如何解决?
解决方案
那是因为实体框架跟踪实体及其变化。因此,一旦您将某些内容加载到上下文中,它将返回该内容。
您需要.AsNoTracking()
在查询上使用
await _context.AcademiesStudents
.AsQueryable()
.AsNoTracking()
.SingleOrDefaultAsync(x => x.Id == id);
推荐阅读
- html - 为网页的最大宽度创建容器
- php - Symfony 单击添加表单行
- html - 从 Webseal 以 HTML 格式显示错误消息
- c - Linux内核驱动程序:轮询硬件寄存器
- python - 从列表嵌套字典返回多个值
- svg - Firefox (88.0.1) 上的 SVG clipPath 问题
- typescript - TypeScript:基于布尔选项参数的返回类型缩小
- python - 在 Python + FastAPI 中,如何访问托管在 Oracle Cloud 上的 VM 中的 Gunicorn 服务网站
- javascript - 如何从对象中创建具有特定键和值的对象数组?
- java - 接口的Spring Boot依赖注入