问题描述
我很难为LINQ查询中的包含项添加一些过滤条件.我的查询就像
I have some difficulty to add some filter condition for included items in my LINQ query. My query is like
var item = _Context.Order.Include("Inner")
.Include("Inner.first")
.Include("Inner.second")
.Where(x => ( !(x.IsDeleted) && (x.IsActive) &&
(x.itemid == id))).FirstOrDefault();
在上面的代码内部"中,是另一个项目列表.现在我需要过滤内部项目.我只需要过滤条件为inner.isDeleted = true的内部项目.
In the above code "Inner" is another list of item. Now i need to filter inner items. I only need inner item with filter condition inner.isDeleted = true.
查询应返回类似的类,
public class Order
{
public string Name { get; set; }
public List<InnerDetails> Inner{ get; set; }
public bool IsDeleted { get; set; }
}
和类似InnerDetails的类
and InnerDetails class like
public class InnerDetails
{
public string Sample { get; set; }
public bool IsDeleted { get; set; }
public int firstId { get; set; }
public int secondID { get; set; }
public First first{ get; set; }
public Second second{ get; set; }
}
有人可以建议我做一个更好的方法,因为我是LINQ和EF的新手吗?
Can anyone suggest me a better approach to do this because i am new in LINQ and EF?
推荐答案
免责声明:我是该项目的所有者实体框架增强版
Disclaimer: I'm the owner of the project Entity Framework Plus
EF +查询IncludeFilter功能允许过滤相关实体.
EF+ Query IncludeFilter feature allows filtering related entities.
var item = _Context.Order
.IncludeFilter(x => x.Inner.Where(y => y.IsDeleted))
.IncludeFilter(x => x.Inner.Where(y => y.IsDeleted).Select(y => y.first))
.IncludeFilter(x => x.Inner.Where(y => y.IsDeleted).Select(y => y.second))
.Where(x => ( !(x.IsDeleted) && (x.IsActive) &&
(x.itemid == id))).FirstOrDefault();
注意:您不能混合使用Include&IncludeFilter.
Note: You cannot mix Include & IncludeFilter.
Wiki: EF +查询IncludeFilter
回答子问题
是的,我的图书馆在幕后使用了与投影相似的解决方案
Yes, under the hood, my library uses a similar solution as projection
var item = _Context.Order.Select(x => new {
Order = x,
Inner = x.Inner.Where(y => y.IsDeleted),
first = x.Inner.Where(y => y.IsDeleted).Select(y => y.first)
second = x.Inner.Where(y => y.IsDeleted).Select(y => y.second)
})
.Where(x => ( !(x.IsDeleted) && (x.IsActive) && (x.itemid == id)))
.FirstOrDefault()
.Select(x => x.Order)
.FirstOrDefault();
注意:代码尚未经过测试
回答评论
从v1.10.0开始,EF Core 2.x现在支持 IncludeFilter
Starting from the v1.10.0, the IncludeFilter
is now supported in EF Core 2.x
请参阅:发行说明
回答子问题
我们还没有 ThenInclude
.
因此,您需要再次将 IncludeFilter
与所有过滤器一起使用,并浏览要包含的列表或实体.
So you need to use IncludeFilter
again with all filter and navigate through the list or entity you want to include.
这篇关于包括过滤器子集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!