Search code examples
c#.netiqueryableeager-loadingobjectquery

How can I convert IQueryable<T> to ObjectQuery<T>?


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?


Solution

  • From the comments to an answer:

    Casting to an ObjectQuery<T> only works when the query really is an ObjectQuery<T>, it won't work on any other IQueryable<T>. Since you're using a DbContext instead of an ObjectContext, the queries are of a different type. However, you do not need to cast to the correct type, the DbExtensions.Include extension methods in the System.Data.Entity namespace accept any IQueryable<T> type, and call the appropriate underlying Include method. You can use this, avoid the cast, and thereby avoid explicitly specifying the query's type in your code.