【问题标题】:EF builds EntityCollection, but I (think I) want IQueryableEF 构建 EntityCollection,但我(想我)想要 IQueryable
【发布时间】:2010-11-30 19:51:41
【问题描述】:

我有一个实体A,带有一个简单的导航属性B。对于A 的任何给定实例,我们预计会有数千个相关的B 实例。

我不会这样称呼:

foreach(var x in A.B) { ... }

相反,我对进行聚合操作感兴趣,例如

var statY = A.B.Where(o => o.Property == "Y");
var statZ = A.B.Where(o => o.CreateDate > DateTime.Now.AddDays(-1));

据我所知,EF 实例化了数千个对 B 的引用并在内存中执行这些操作。这是因为导航属性使用 EntityCollection。相反,如果可能,我希望它在 SQL 级别执行这些查询。

我目前的预感是导航属性可能不是正确的方法。我不依赖 EF,所以我对其他方法持开放态度。但如果可能的话,我很想知道在 EF 下执行此操作的正确方法。

(我正在使用 EF4。)

【问题讨论】:

    标签: entity-framework iqueryable


    【解决方案1】:

    CreateSourceQuery 似乎可以解决问题。

    所以我现在的例子是:

    var statY = A.B.CreateSourceQuery().Where(o => o.Property == "Y");
    var statZ = A.B.CreateSourceQuery().Where(o => o.CreateDate > DateTime.Now.AddDays(-1));
    

    【讨论】:

    • 去 A.Where(a=>a.B.CreateSourceQuery().Any(o => o.Property == "Y"));还是在这种情况下推荐使用 linq JOIN?
    【解决方案2】:

    有一件事你应该知道。从 IQueryable 派生的成员在服务器上执行,而不是在内存中。从 IEnumerable 派生的成员在内存中执行。 例如

    var someEntities = db.SomeEntities; <-- returns an IQueryable<> object. no data fetched. SomeEntities table may contain thousands of rows, but we are not fetching it yet, we are just building a query.
    someEntities = someEntities.Where(s => s.Id > 100 && s.Id < 200); <-- creates expression tree with where statement. The query is not executed yet and data is not fetched on the client. We just tell EF to perform a where filter when query will execute. This statement too returns an IQueryable<> object.
    var entities = someEntities.AsEnumerable(); <-- here we tell EF to execute query. now entities will be fetched and any additional linq query will be performed in memory.
    

    您还可以使用 foreach 获取数据,调用 ToArray() 或 ToList。

    希望你明白我的意思,对不起我的英语:)

    【讨论】:

    • 是的,我明白这一切。但是,问题在于导航属性是 EntityCollections 并且不实现 IQueryable。
    • 此答案与问题无关。. 问题询问实体公开的 NavigationProperties 上的 EntityCollections,而您的回答侧重于解释如何对 @ 公开的 ObjectSet 进行操作987654324@s。简而言之,OP 询问如何在背包中找到某物,而您的答案则说明如何在汽车后备箱中找到背包。
    猜你喜欢
    • 2013-09-18
    • 2021-12-12
    • 2022-10-19
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 2014-05-02
    • 2015-07-13
    • 2021-05-26
    相关资源
    最近更新 更多