[英]LINQ to Entities, Where Any In
How to write 'Where Any In' in LINQ to Entity? 如何在LINQ中将“凡在何处”写入实体?
Here is my model : 这是我的模型:
class Chair
{
public int Id { get; set; }
public int TableId { get; set; }
public Table Table { get; set; }
}
class Table
{
public int Id { get; set; }
public ICollection<Chair> Chairs { get; set; }
public ICollection<Category> Categories { get; set; }
public Table()
{
Chairs = new List<Chair>();
Categories = new List<Category>();
}
}
class Category
{
public int Id { get; set; }
public ICollection<Table> Tables { get; set; }
}
I also got a simple list of Category : 我还得到了一个简单的Category列表:
List<Category> myCategories = new List<Category>(c,d,e);
I want to get only that Chairs that belongs to Table that got one of the Category from myCategories List. 我只想获得属于myTable列表中属于类别之一的Table的椅子。 Thats what im trying to do : 那就是我想做的事情:
var result =
ctx.Chairs.Where(x => x.Table.Categories.Any(y => myCategories.Any(z => z.Id == y.Id))).ToList();
I think its ok but what i get is error : 我认为可以,但是我得到的是错误:
"Unable to create a constant value of type 'ConsoleApplication1.Category'. Only primitive types or enumeration types are supported in this context" “无法创建类型'ConsoleApplication1.Category'的常量值。在此上下文中仅支持原始类型或枚举类型”
this is because ctx.Chairs
is a collection that is in database, you should retrieve that collection first in order to compare it with in-memory data: 这是因为ctx.Chairs
是数据库中的一个集合,您应该首先检索该集合才能将其与内存中的数据进行比较:
var result = ctx
.Chairs
.AsEnumerable() // retrieve data
.Where(x =>
x.Table.Categories.Any(y =>
myCategories.Any(z => z.Id == y.Id)))
.ToList();
EDIT: that wouldn't be the correct thing to do if you have a lot of entities on database, what you can do is to split it into two queries: 编辑:如果您在数据库上有很多实体,那将不是正确的事情,您可以做的是将其分为两个查询:
var tables = ctx.Tables
.Where(x =>
x.Categories.Any(y =>
myCategories.Any(z => z.Id == y.Id)));
var result = ctx.Chairs
.Where(x =>
tables.Any(t=> t.Id == x.TableId))
.ToList();
You can select Ids from myCategories and use it last statement. 您可以从myCategories中选择ID,然后在最后一个语句中使用它。
var CategoryIds = myCategories.Select(ct => ct.Id);
var result = ctx.Chairs.Where(x => x.Table.Categories.Any(y => CategoryIds.Any(z => z == y.Id))).ToList();
Try to compare with in-memory categories Ids collection, instead of categories collection. 尝试与内存中类别Ids集合进行比较,而不是与类别集合进行比较。
var myCategoriesIds = myCategories.Select(c => c.Id).ToArray();
var result =
context.Chairs
.Where(
x => x.Table.Categories.Any(
y => myCategoriesIds.Contains(y.Id)))
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.