表达式中的EF Core 3 x.Contains(),其中x是ICollection [英] EF Core 3 x.Contains() in expression where x is ICollection

查看:415
本文介绍了表达式中的EF Core 3 x.Contains(),其中x是ICollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了以下数据层:

I've got the following data layer setup:

public class Repository : IRepository {

    private readonly MyDbContext _dbContext;

        public List<Meter> Search(Expression<Func<Meter,bool>> criteria)
            IQueryable<Meter> results = _dbContext.Meters;
            return results.Where(criteria).ToList();
        }
    }
}

... from a client class:

IRepository _repository;

public void ClientMethod () {

    ICollection<int> ids = new List<int>() {1, 2, 3);
    var results = _repository.Search(c=> ids.Contains(c.Id)); // This throws exception

}

这将导致异常:


expression where(源​​:DbSet,谓词:(m)=>
(未处理的参数:__ids_0)。包含(m。 Id))'无法翻译
。可以将查询重写为
的形式,也可以通过插入对
的调用AsEnumerable(),AsAsyncEnumerable(),ToList()或ToListAsync()来显式转换为客户端评估。

expression Where(source: DbSet, predicate: (m) => (Unhandled parameter: __ids_0).Contains(m.Id))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()

但是如果我将集合引用更改为IEnumerable或List,它将起作用:

But if I change the collection reference to IEnumerable or List, it works:

public void ClientMethod () {

    // This works
    List<int> ids = new List<int>() {1, 2, 3);
    var results = _repository.Search(c=> ids.Contains(c.Id)); 

    // This works
    IEnumerable<int> ids = new List<int>() {1, 2, 3);
    var results = _repository.Search(c=> ids.Contains(c.Id)); 
}

为什么对ICollection不起作用,对IEnumerable和List起作用?我的许多客户端方法都将ICollection作为参数。

Why is it not working for ICollection, but it does for IEnumerable and List? Many of my client methods take an ICollection as a parameter.

我使用的是EF Core 3.0,但我认为我在2.1中也遇到了同样的问题,只是没有

I'm using EF Core 3.0 but I believe I had the same problem in 2.1, it just didn't throw as it evaluated it on the client instead.

推荐答案

在迁移到EF Core 3.0时,我遇到了同样的问题从2.2版开始。我已经配置了ef,以便在客户端评估时出错,并且工作正常。因此,我确定这是3.0版中的新问题,在他们重写linq引擎时引入。

I've run into the same issue, when migrating to EF Core 3.0 from 2.2. I've had ef configured before to throw error on client side evaluation, and it was working fine. So I'm sure it's a new issue with 3.0, introduced when they've rewritten the linq engine.

将其投放到IEnumerable或List也适用于我,谢谢小费!

Casting it to either IEnumerable or List works for me as well, thanks for the tip!

这篇关于表达式中的EF Core 3 x.Contains(),其中x是ICollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆