I’m trying to apply the advice in this post: Tip 22 – How to make Include really Include
It suggests a workaround for ensure eager loading works in the Entity Framework (4.2). That workaround involves casting the IQueryable to an ObjectQuery.
However, when I attempt this, as shown in the post, the query returns a null.
My query is (ctx is a 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;
That works as expected.
However, when I use,
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>;
it assigns a null to “coupons”.
Any idea what I’m doing wrong?
From the comments to an answer:
Casting to an
ObjectQuery<T>only works when the query really is anObjectQuery<T>, it won’t work on any otherIQueryable<T>. Since you’re using aDbContextinstead of anObjectContext, the queries are of a different type. However, you do not need to cast to the correct type, theDbExtensions.Includeextension methods in theSystem.Data.Entitynamespace accept anyIQueryable<T>type, and call the appropriate underlyingIncludemethod. You can use this, avoid the cast, and thereby avoid explicitly specifying the query’s type in your code.