无法将类型为“ System.Linq.EnumerableQuery`1 [Entities.Test]”的对象强制转换为类型为“ System.Data.Objects.ObjectQuery`1 [Entities.Test]”的对象

Pol*_*Pol 5 .net c# linq-to-entities entity-framework ef-code-first

我正在使用Entity Framework 4.2(EntityFramework.dll v4.0.30319)Code First,并具有LINQ查询,该查询可以简化为:

IQueryable<Test> testQuery = from test in repository.Tests select test;
Run Code Online (Sandbox Code Playgroud)

repository.TestsIQueryable<Test>直接实现为DbSet<Test>在Enity框架的DbContext

我注意到我的查询在某种程度上区分大小写,而Microsoft SQL Server数据库中的区分大小写排序规则。可疑,所以我想跟踪SQL。但是当我这样做时:

var trace = ((ObjectQuery<Test>)testQuery).ToTraceString();
Run Code Online (Sandbox Code Playgroud)

我得到异常:

无法转换类型为'System.Linq.EnumerableQuery 1[Entities.Test]' to type 'System.Data.Objects.ObjectQuery1 [Entities.Test]'的对象。

为什么会这样?

Lad*_*nka 5

您正在组合两个不同的API-ObjectContext API和DbContext API。您不能转换从创建的查询DbSetObjectQuery而只能转换到DbQuery与不相关的查询ObjectQuery

您可以通过以下方式轻松实现您想做的事情:

var trace = testQuery.ToString();
Run Code Online (Sandbox Code Playgroud)