首页 > 解决方案 > 实体框架在下一个查询中包含持久性

问题描述

我正在尝试执行条件包含查询。我看到了多种选择,其中之一是投影。我还需要能够访问过滤列表中的属性。

实体之间的关系是:

(Parent) 1-n (List of children) 1-1 (Grand Child)

我尝试了选项 whit projection 并且它有效,但我无法从过滤列表中访问该属性。我花了很多时间试图让它工作,并使用“尝试失败的方法”我设法做到了,但我注意到一些我不明白的事情,这让我很困扰。这是我的代码:

    public IQueryable<Parent> Parents()
    {
        GrandChildId = ....;

        _contextProvider.Context.Parents.Where(c => "condition").Include(b =>
            b.ChildrenList.Select(f => f.GrandChild)).ToList();    //PART 1------------------

        var parentsList = _contextProvider.Context.Parents.Where(condition).Select(parents => new
                                                                        {
                                                                            Parents = parents,
                                                                            ChildrenList = parents.ChildrenList.Where(b => b.GrandChild.Id == GrandChildId),
                                                                        }
            ).ToList().Select(row =>
                {
                    var item = row.Parents;
                    item.ChildrenList = (ICollection<ChildrenList>)row.ChildrenList;
                    
                    return item;
                }
            ); //PART 2--------------------

        return parentsList.AsQueryable();
    }

如果您问我,我认为“第 1 部分”无关紧要,但如果我删除它并尝试将包含放在“第 2 部分”上,则不再起作用(不再可以访问孙子)。似乎第一部分的包含持续到第二个查询。

所有导航属性都是“虚拟的”。

标签: entity-framework-6lazy-loading

解决方案


推荐阅读