Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cast object of type 'System.Linq.EnumerableQuery`1[Entities.Test]' to type 'System.Data.Objects.ObjectQuery`1[Entities.Test]'

I'm using Entity Framework 4.2 (EntityFramework.dll v4.0.30319) Code First and have a LINQ query which can be simplified to:

IQueryable<Test> testQuery = from test in repository.Tests select test;

The repository.Tests is IQueryable<Test> implemented directly as DbSet<Test> in Enity Framework's DbContext.

I noticed that my queries are somehow case-sensitive with case-insensitive collation in Microsoft SQL Server Database. Suspicious, so I wanted to trace the SQL. But when I do this:

var trace = ((ObjectQuery<Test>)testQuery).ToTraceString();

I get exception:

Unable to cast object of type 'System.Linq.EnumerableQuery1[Entities.Test]' to type 'System.Data.Objects.ObjectQuery1[Entities.Test]'.

Why this happens?

like image 236
Pol Avatar asked Feb 28 '12 09:02

Pol


1 Answers

You are combining two different APIs - ObjectContext API and DbContext API. You cannot cast query created from DbSet to ObjectQuery but only to DbQuery which is not related to ObjectQuery.

What you want to do can be easily achived by:

var trace = testQuery.ToString();
like image 106
Ladislav Mrnka Avatar answered Oct 11 '22 15:10

Ladislav Mrnka