我可以使用 Entity Framework 4 使用“.Include”加载分层数据吗?并根据某些条件过滤导航属性
您好,我正在使用实体框架 4,我正在尝试查询客户及其订单 作为导航属性,但我只想加载特定日期的订单。
使用此功能时:
List<Customer> CustomerResults = ctx.Customers
.Include("Orders")
.Where(
c =>
c.Orders.Any(od =>(od.DateTimeIn >= this.StartDateComboBox.DateTime &&
od.DateTimeIn <= this.EndDateComboBox.DateTime))
);
如果任何订单符合条件,我会收到所有订单。
是否可以过滤导航属性以仅返回满足特定条件的行?
Hello I am using entity framework 4 and I am trying to query Customers and their Orders
as navigation property, but I only want to load the orders of a specific date.
When using this:
List<Customer> CustomerResults = ctx.Customers
.Include("Orders")
.Where(
c =>
c.Orders.Any(od =>(od.DateTimeIn >= this.StartDateComboBox.DateTime &&
od.DateTimeIn <= this.EndDateComboBox.DateTime))
);
I get all Orders, if any of the Orders meet the criteria.
Is It possible to filter the navigation property to return only rows that meet specific criteria?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,没有。
简而言之,使用
Include
进行急切加载会自动加载所有相关记录(想象一下没有过滤器的 LEFT OUTER JOIN)。任何时候您想要过滤关联记录时,都不要使用
Include
- 使用匿名类型投影,EF 只会“计算出”需要检索的内容:如果您想返回
Customer
实体,然后在最后进行另一个投影,只需确保首先具体化查询 (.ToList()
)。编辑 - 要放回客户对象,例如:
我确信您可以使用 LINQ 表达式来做到这一点,但我不记得语法了。
No, there isn't.
In short, eager-loading with
Include
automatically loads all related records (think a LEFT OUTER JOIN without a filter).Anytime you want to filter associated records, don't use
Include
- use an anonymous type projection and EF will just "work out" what needs to be retrieved:If you want to return a
Customer
entity, then just do another projection at the end, just make sure you materialize the query first (.ToList()
).EDIT - To put back into a customer object, example:
I'm sure you can do that with a LINQ expression, but i can't remember the syntax.