首页 > 解决方案 > 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;
}

我的问题在哪里?以及如何解决?

标签: c#asp.net-core-3.1ef-core-3.1

解决方案


那是因为实体框架跟踪实体及其变化。因此,一旦您将某些内容加载到上下文中,它将返回该内容。

您需要.AsNoTracking()在查询上使用

await _context.AcademiesStudents
              .AsQueryable()
              .AsNoTracking()
              .SingleOrDefaultAsync(x => x.Id == id);

推荐阅读