EF 4 Code First - Problem while using inner query
I'm having problem using queries like this with Entity Framework 4 Code First:
var entities = context.TestEntities.Where( e => context.TestEntities2.Count() > 0)
The above query will generate the following exception:
Unable to create a constant value of type 'TestModel.TestEntities2'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
The same code works if I use the model designer and generate the POCO-classes and thus using a ObjectContext instead.
EDIT: It works in a console-application but not while using my repository in an MVC 3 project.
EDIT 2: How about this:
var userProfile = ctx.UserProfiles.Where(p => p.User.Id == user.Id).SingleOrDefault();
return ctx.Feeds.Where( f => ctx.ProfileFollowers.Count() > 0 ).ToList();
The above two lines throws the exception. Commenting out the fi开发者_JAVA百科rst line solves the problem. Bug in DbContext?
//var userProfile = ctx.UserProfiles.Where(p => p.User.Id == user.Id).SingleOrDefault();
return ctx.Feeds.Where( f => ctx.ProfileFollowers.Count() > 0 ).ToList();
Posted to http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/2fb5ceea-9f30-4665-af98-945c6485f60b
Try the Any method:
var q = context.TestEntities.Where(a=>context.TestEntities2.Any());
This code results in the EXISTS clause:
SELECT
[Extent1].[ProductID] AS [ProductID],
...
FROM [dbo].[Products] AS [Extent1]
WHERE EXISTS (SELECT
1 AS [C1]
FROM [dbo].[Regions] AS [Extent2]
UPD: In case of repositories the correct way is to execute the first query and then the second one:
if(context.TestEntities2.Count() > 0)
var q = context.TestEntities.Select(t=>t);
精彩评论