【问题标题】:EF Core DBContext caching resultsEF Core DBContext 缓存结果
【发布时间】:2023-03-23 16:50:01
【问题描述】:

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

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

相关实体:UnitPropertyA

相关实体:UnitPropertyB

我检索 Unit 及其通过 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)

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

【问题讨论】:

  • 也许这是 Data 的问题,这意味着 UnitPropertyA 和 UnitPropertyB 中的数据相同
  • 感谢@ElyasEsna!我认为原因可能是应用过滤包含时,结果将“累积”。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2016-10-10
    • 2021-05-09
    相关资源
    最近更新 更多