实体框架包括过滤器子集合 [英] Entity Framework include filter child collection

查看:283
本文介绍了实体框架包括过滤器子集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些困难,为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是项目的另一个列表。现在我需要过滤内部物品。我只需要具有过滤条件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.

查询应该返回一个类,如

Query should return a class like,

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

推荐答案

免责声明:我是项目的所有者 Entity Framework Plus

Disclaimer: I'm the owner of the project Entity Framework Plus

EF + Query IncludeFilter功能允许过滤相关实体。

EF+ Query IncludeFilter feature allow 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();

注意:您不能混合包含&& IncludeFilter。

Note: You cannot mixte Include && IncludeFilter.

维基: EF + Query IncludeFilter

编辑:答案子问题


但是我们可以使用EF实现这一点

But we can achieve this using EF only

是的,在引擎盖下,我的图书馆使用类似的解决方案投影

Yes, under the hood, my library use 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();

注意:代码尚未测试

这篇关于实体框架包括过滤器子集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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