代码之家  ›  专栏  ›  技术社区  ›  Zachary Scott

如何创建和填充嵌套视图模型

  •  0
  • Zachary Scott  · 技术社区  · 14 年前

    我有一个视图模型有一些严重的嵌套。我需要从实体框架4填充它。我试图创建一个大的linq语句来填充它,但它说它不能识别.ToList()方法。它汇编得很好。运行时错误是

    LINQ to Entities does not recognize the method 
    'System.Collections.Generic.List`1[ProductDepartment] ToList[ProductDepartment]
    (System.Collections.Generic.IEnumerable`1[ProductDepartment])' method, 
    and this method cannot be translated into a store expression.
    

    在不进行几千次数据库调用的情况下,如何更有效地填充这样的内容?

    List<Product> Products {
        int ID
        string Name
        ...
        List<Department> Departments {
            int ID
            string Name
        }
        List<Image> Images {
            int ID
            string Name
        }
        List<Price> Prices {
            int ID
            string Name
            List<Version> Versions {
                int ID
                string Name
                List<Pages> Pages {
                    int ID
                    string Name
    }   }   }   }
    

    var myProducts = (from myProduct in DC.MyProducts
                      where p => p.productGroup == 1
                      select new Product {
                          ID = myProduct.ID,
                          Name = myProduct.Name,
                          Departments = (from myDept in DC.MyDepartments
                                         where q => q.fkey = myProduct.pkey
                                         select new Department {
                                             ID = myDept.ID,
                                             Name = myDept.Name
                                         }).ToList(),
                          ...
                          //Same field assignment with each nesting
                      }).ToList();
    

    更新:

    现在我必须对最终产品进行过滤和排序。

    2 回复  |  直到 14 年前
        1
  •  1
  •   RPM1984    14 年前

    首先,这是一个疯狂的模式,但我想你已经知道了。

    你真的 所有的信息一次?

    我在这里扮演魔鬼代言人的角色,假设你是,在这种情况下,你有两个逻辑选择:

    .包括 在一个调用中立即加载您的关联。这假设您在EDMX中为实体设置了导航属性。

    2) 使用视图。将所有疯狂的连接逻辑放入数据库中,使您的EF从视图中非常简单地选择工作。这样做的缺点是您对视图的查询基本上变成只读的,因为我不相信您可以对映射到视图的实体执行更新。

    因此,这是您的选择-如果这是一个用于显示数据的只读集合,请使用视图,否则将立即加载您的关联。

    另外,在编写LINQ查询时要小心——我看到有多个.ToList语句,这将导致执行查询。

        2
  •  1
  •   TalentTuner    14 年前

    你为什么一次就要这些信息?访问嵌套属性时可以使用延迟加载?