Current implementation of DbQueryVisitor tries to handle cases where the query is closed over variables containing DbQuery values by simply replacing them with the underlying ObjectQuery instances. Obviously, if the query is closed over a variable of type DbSet the assignment will fail.
Following code will throw System.ArgumentException: Object of type 'System.Data.Objects.ObjectQuery`1[AnyEntity]' cannot be converted to type 'System.Data.Entity.DbSet`1[AnyEntity]':
using (var anyContext = new AnyContext())
{
var anySet = anyContext.Set<AnyEntity>();
var query = from x in anyContext.Set<AnyOtherEntity>()
from y in anySet
select new { x, y };
// change the type of the anySet variable to IQueryabe and the exception is gone
// but guess what's the value of the anySet variable now
}
Also changing the value of closed variable doesn't seem right for me (simple query construction now has side effects).
Possible solution is to rewrite Constant->Field(DbSet) expression to Constant(ObjectContext) expression.
Comments: Long term we think the right solution is to update Linq To Entities to recognize DbSet's and DbQuery's in the same way that it recognizes ObjectSet's and ObjectQuery's at the moment. But this is a larger, longer-term project which will will attempt later on. For the moment we will encourage users to use the workaround (i.e. setting the mySet variable explicitly to IQueryable).
Following code will throw System.ArgumentException: Object of type 'System.Data.Objects.ObjectQuery`1[AnyEntity]' cannot be converted to type 'System.Data.Entity.DbSet`1[AnyEntity]':
using (var anyContext = new AnyContext())
{
var anySet = anyContext.Set<AnyEntity>();
var query = from x in anyContext.Set<AnyOtherEntity>()
from y in anySet
select new { x, y };
// change the type of the anySet variable to IQueryabe and the exception is gone
// but guess what's the value of the anySet variable now
}
Also changing the value of closed variable doesn't seem right for me (simple query construction now has side effects).
Possible solution is to rewrite Constant->Field(DbSet) expression to Constant(ObjectContext) expression.
Comments: Long term we think the right solution is to update Linq To Entities to recognize DbSet's and DbQuery's in the same way that it recognizes ObjectSet's and ObjectQuery's at the moment. But this is a larger, longer-term project which will will attempt later on. For the moment we will encourage users to use the workaround (i.e. setting the mySet variable explicitly to IQueryable).