How to convert IQueryable <T> to ObjectQuery <T>?
I am trying to apply advice in this post: Tip 22 - How to enable Enable really Enable
It offers a workaround for providing reliable boot operations in the Entity Framework (4.2). This method involves casting IQueryable in ObjectQuery.
However, when I try to do this, as shown in the message, the query returns zero.
My request (ctx is 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; This 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 null to "coupons".
Any idea what I'm doing wrong?
From the comments to the answer:
Listing ObjectQuery<T> only works when the query is really ObjectQuery<T> , it will not work on any other IQueryable<T> . Since you are using a DbContext instead of an ObjectContext , the requests are of a different type. However, you do not need to specify the correct type; the extension methods DbExtensions.Include in the System.Data.Entity namespace accept any type of IQueryable<T> and call the corresponding base Include method. You can use this, avoid casting, and thereby avoid explicitly specifying the type of request in your code.
What you do is equivalent to this
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; ObjectQuery<Coupon> converted = coupons as ObjectQuery<Coupon>; with coupons not null and converted null.
This means that the order is missing.
This does not solve your problem, but at least identifies it.
Perhaps you are using a different version of Entity Framework?