【问题标题】:LINQ query select entity and its collection queryLINQ 查询选择实体及其集合查询
【发布时间】:2014-10-08 14:27:01
【问题描述】:

我有一个名为 Parent 的实体,其中包含子列表。 现在我想按显示顺序选择一个父级及其所有子级。

    entities:- class parent{
                          Int id;
                          List<Child> children;
                           }

                class Child{ 
                            String name;
                            DateTime DOB;
                            Int DisplayOrder;
                           }

之前我使用 Linq to Entity 从数据库获取父级

                context.Parents.Find(id);

这一切都很好。但现在我的要求发生了变化,现在我需要按显示顺序选择其子顺序。我怎样才能做到这一点。任何帮助表示赞赏。

更新父类:-

              class parent{
                        public  Int id;
                        public virtual List<Child> children;
                           }

【问题讨论】:

    标签: asp.net linq c#-4.0 entity-framework-6.1


    【解决方案1】:

    根据您提供的信息,我猜您在某处使用您的children 来显示它们,因此您可以只使用parent.children.OrderBy(x =&gt; x.DisplayOrder).ToList() 而不是我想您以前使用的简单的parent.children

    更新 1。

    据我所知,Find 不包括您的孩子。非常值得尝试类似的东西:

    var parent = context.Parents.Include(x => x.children).FirstOrDefault(x => x.id = id);
    parent.children = parent.children.OrderBy(x => x.DisplayOrder).ToList();
    

    【讨论】:

    • 不,我在 .cshtml 文件中访问了 model.children,我使用了 for 循环而不是 foreach。我无法改变这就是为什么我问我是否可以从数据库本身按排序顺序获得带孩子的父母
    • @iGod 我很确定你可以改变它,只是告诉你用法?您将能够创建另一个局部变量,您将在其中存储重新排序的 children,并且您将能够针对该变量进行循环。
    • 嗨弗拉德,反对您更新的评论(对不起,我正在使用它)。 find 也包括孩子,刚才我想出了这个解决方案“parent.children = parent.children.OrderBy(x => x.DisplayOrder).ToList()”。但这样好吗?
    • @iGod 这取决于您的应用程序设计和平均子记录数量,但无法选择具有有序子记录的父级。您唯一可以在那里做的事情 - 在 SQL 服务器端执行该排序:从 p in context.Parents.Find(id) select new {id = p.id, children = p.children.OrderBy(c => c.DisplayOrder) }
    【解决方案2】:

    您在列表中有 Order By 命令,您可以将“列”发送给控制器并按此列排序

    【讨论】:

    • 我没有t get your point. i need to fetch a parent based on id passed and all its 孩子也按显示顺序排序
    • 但你可以使用 context.Parents.Find(id).OrderBy(order => order.DisplayOrder);
    • 它不起作用,因为您不能在 Find() 之后使用 orderby 扩展。而且显示顺序属性适用于非父级的子级
    【解决方案3】:

    这是在您确定只能有一个具有给定 ID 的父母的情况下。

    var parent = context.Parents.Find(id);
    parent.children = parent.children.OrderBy(cl => cl.DisplayOrder).ToList();
    

    【讨论】:

    • 我也是这么想的。但我怀疑这是正确的方法
    • @iGod 确定它工作正常。但也许这不是最好的解决方案。订购 parent.children 本身不起作用。
    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 2021-08-12
    • 2012-03-24
    相关资源
    最近更新 更多