[英]Filter DbSet by list of objects
I am using Entity Framework Core with SQL Server to filter a list of division entities by a list of passed in search objects.我将 Entity Framework Core 与 SQL Server 一起使用,通过传入的搜索对象列表过滤部门实体列表。 I want to return division that match the criteria in any one of the search objects.
我想返回与任何一个搜索对象中的条件匹配的除法。 The search object class looks like:
搜索对象类如下所示:
public class SearchObject
{
public int DivisionId { get; set; }
public int Status { get; set; }
}
Here is the query I tried:这是我尝试的查询:
var searchObjects = new List<SearchObject> { ... };
IQueryable<Product> query = myContext.Divisions.Where(div =>
searchObjects.Any(searchObj =>
searchObj.Status == div.Status &&
searchObj.DivisionId == div.DivisionId))
.Select(...);
When the IQueryable enumerates, I get an error stating: "The Linq Expresion DbSet ... Could not be translated ..." What I need is something like .Contains(), but that works with a list of SearchObj.当 IQueryable 枚举时,我收到一条错误消息:“Linq 表达式 DbSet ......无法翻译......”我需要的是类似 .Contains() 的东西,但它适用于 SearchObj 列表。
Well you have the right idea by那么你有正确的想法
What I need is something like .Contains(), but that works with a list of SearchObj.
我需要的是类似 .Contains() 的东西,但它适用于 SearchObj 列表。
and this is how you'd do it这就是你的做法
var searchObjects = new List<SearchObject> { ... };
var searchIds = searchObjects.Select(x => x.Divisiond) //.ToList() perhaps?
var searchStatus = searchObjects.Select(x => x.Status) //.ToList() perhaps?
//not you can simply use .Contains and it should generate a WHERE EXISTS query
IQueryable<Product> query = myContext.Divisions
.Where(div =>
searchIds.Contains(div.DivisionId) &&
searchStatus.Contains(div.Status))
.Select(...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.