gpt4 book ai didi

c# - 如何将 IQueryable 转换为 ObjectQuery

转载 作者:太空狗 更新时间:2023-10-30 00:27:00 26 4
gpt4 key购买 nike

我正在尝试应用这篇文章中的建议:Tip 22 - How to make Include really Include

它提出了一种解决方法,以确保预先加载在 Entity Framework (4.2) 中正常工作。该解决方法涉及将 IQueryable 转换为 ObjectQuery。

但是,当我尝试这样做时,如帖子中所示,查询返回空值。

我的查询是(ctx 是一个 DbContext):

IEnumerable<Coupon> coupons =
from x in ctx.Coupons
where x.LanguageCode.Equals("EN", StringComparison.InvariantCultureIgnoreCase) && x.CategoryId == MainCategoryId && x.Date >= fromDate && x.Date <= toDate
select x;

这按预期工作。

但是,当我使用的时候,

IEnumerable<Coupon> coupons =
(from x in ctx.Coupons
where x.LanguageCode.Equals("EN", StringComparison.InvariantCultureIgnoreCase) && x.CategoryId == MainCategoryId && x.Date >= fromDate && x.Date <= toDate
select x) as ObjectQuery<Coupon>;

它为“优惠券”分配了一个空值。

知道我做错了什么吗?

最佳答案

从评论到回答:

转换为 ObjectQuery<T>仅当查询确实是 ObjectQuery<T> 时有效, 它不适用于任何其他 IQueryable<T> .由于您使用的是 DbContext而不是 ObjectContext ,查询属于不同类型。但是,您不需要转换为正确的类型,DbExtensions.IncludeSystem.Data.Entity 中的扩展方法命名空间接受任何 IQueryable<T>类型,并调用适当的基础 Include方法。您可以使用它,避免强制转换,从而避免在您的代码中明确指定查询的类型。

关于c# - 如何将 IQueryable<T> 转换为 ObjectQuery<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8535864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com