【问题标题】:EF core, Any could not be translated and will be evaluated locallyEF 核心,Any 无法翻译,将在本地评估
【发布时间】:2022-04-02 07:14:00
【问题描述】:

我有一个程序可以返回我需要的实体 ID。

(我决定创建这个过程,因为应该返回给最终用户的实体会被相关实体过滤,但 EF Core 不支持被相关实体过滤)。

然后我想使用这个 id 来获取我需要的实体与他们的相关实体。

我正在使用Any operator. In my opinion it should generate query like this: WHERE id IN(1,2,3,4....)`,但它似乎不像我想要的那样工作。

相反,它会返回带有以下信息的警告:

任何子句都无法翻译,将在本地进行评估

我该如何解决?

我的代码如下:

var assocsIds = await _context.Assoc.AsNoTracking()
.FromSql($"exec {SqlProcedures.GetAssocsForIndexProc} {query.IndexMviId}, {query.FilterByGroupId}")
.ToListAsync()

var productAssocs = await _context.Assoc
    .Where(x => assocsIds.Any(z => z.Id == x.Id))
    .Include(x => x.Attribute)
    .ThenInclude(x => x.Translation)
    .Include(x => x.Option)
    .ThenInclude(x => x.Translation)
    .Include(x => x.Mvi)
    .ThenInclude(x => x.Translation)
    .AsNoTracking()
    .ToListAsync()
;

【问题讨论】:

  • var assocsIds = await _context.Assoc.AsNoTracking() .FromSql($"exec {SqlProcedures.GetAssocsForIndexProc} {query.IndexMviId}, {query.FilterByGroupId}") .ToListAsync() var bob = assocsIds.Select(z => z.Id).ToList(); var productAssocs = await _context.Assoc .Where(x => bob.Contains(x.Id) .etc etc 工作吗?

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


【解决方案1】:

您可以先从 assocsIds 中选择“Id”到另一个变量中,然后尝试以下操作吗?

var productAssocs = await _context.Assoc
            .Where(x => yourIdsList.Contains(x.Id))
            .Include(x => x.Attribute)
            .ThenInclude(x => x.Translation)
            .Include(x => x.Option)
            .ThenInclude(x => x.Translation)
            .Include(x => x.Mvi)
            .ThenInclude(x => x.Translation)
            .AsNoTracking()
            .ToListAsync();

【讨论】:

  • 你是对的。但是我曾经读过,它不应该使用包含,人们建议使用任何运算符来代替
  • 这并不能解释为什么它会起作用?一个好的答案包括解释。
  • 显然它可以工作“...因为 EF 可以翻译 Contains(),但不能翻译 Any()” (@RobertHarvey)。
猜你喜欢
  • 1970-01-01
  • 2017-12-27
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 2020-12-27
  • 1970-01-01
相关资源
最近更新 更多