本文介绍了实体框架延迟加载和ICollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个叫Stock的类,它有一个虚拟的ICollection Price,它是一组历史价格。

Lets say that I have a class called Stock and which has a virtual ICollection Prices, which is a historical set of prices.

如果您获取股票并之后您查询价格,但要应用股票,但要应用mystock.Prices.OrderByDescending(px => px.Date).First()之类的过滤器,EF会内部加载所有价格,然后应用所使用的过滤器,因为价格可能是大量收藏,我真的很想看到EF只需加载符合我所在条件的价格。基本上,将过滤应用于服务器端而不是客户端。

If you fetch a stock and after the stock is materialized you query the Prices but apply a filter like mystock.Prices.OrderByDescending(px => px.Date).First(), EF internally loads all the prices and then it applies the filters used, since prices could be a large collection, I would really like to see EF just load the price that matched my where criteria. Basically applying the filtering at the server end rather than client side.

有可能这样做吗?

谢谢

推荐答案

有可能,但是只有当您可以假设价格实际上是 EntityCollection ,而不是其他也实现了 ICollection 的其他类。我不确定在所有受支持的EF场景中是否都是如此。使用的函数是 EntityCollection 的函数。

It's possible, but this way only works if you can assume Prices is really an EntityCollection rather than some other class that also happens to implement ICollection. I'm not sure if this is true in all supported EF scenarios. The function to use is EntityCollection's CreateSourceQuery function.

((EntityCollection<Price>)stock.Prices).CreateSourceQuery().OrderByDescending(price => price.Date).First();

如果这对您不起作用,则另一种可能是返回上下文,并且从那里查询:

If that doesn't work for you, another possibility might be to go back to the context, and query from there:

(from price in context.Prices
 where price.StockId == stockId
 orderby price.Date descending
 select price).First();

这篇关于实体框架延迟加载和ICollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:30