EF Core DBContext 缓存结果

时间:2021-04-16 20:14:58

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

我有一个 .net 核心 API,其中包括一个数据层,所有数据检索和操作都在其中发生。 DB 上下文被注入到 Startup 中,并且 repo 类都从传递 db 上下文的基本 repo 类继承。在一种特定的方法中,我必须循环记录并获取符合特定条件的相关实体。我注意到在循环的第二轮中,即使前一个循环中的相关实体不符合过滤条件,也会返回它们,并且生成的 sql 查询在直接在服务器上执行时返回正确的记录数。为了说明这里发生的事情,以下是详细信息:

Entity:Unit(每个unit在两种不同的语言下分别有两个UnitPropertyA和两个UnitPropertyB)

相关实体:UnitPropertyA

相关实体:UnitPropertyB

我检索单元及其通过languageId过滤的相关实体的代码如下

(通过在 repo 中调用以下方法开始在业务层中为每个 languageId 循环):

public async Task<Unit> GetUnitByLangIdAsync(int Id, int langId)
{

       var result = await _context.Unit
        .Where(x => x.UnitId == Id)
        .Include(x => x.UnitPropertyA.Where(i => i.LanguageId == langId).OrderByDescending(i => i.Id)).Take(1)
        .Include(x => x.UnitPropertyB.Where(i => i.LanguageId == langId).OrderByDescending(i => i.Id)).Take(1)                      
        .FirstOrDefaultAsync();

        return result;(result returned to the business layer)
}
(...end loop in the business layer)

我注意到这将为我提供第一种语言的正确结果,而第二种语言的结果将包括上一次迭代(即第一种语言)的记录。我错过了什么吗? 任何提示表示赞赏!

1 个答案:

答案 0 :(得分:0)

找了将近一天的答案,我想我找到了答案。原因可能是在同一个数据库上下文中应用过滤的包含时,结果将“累积”。