Search code examples
linqlinq-to-entitiesincludeprojection

Can I do a "Take(x)" on the "Include" entity in a Linq Query?


i've got a really simple linq to entites statement :-

var query = (from q in Users.Include("UserHistory")
            select q).Take(20);

works great ... except that, for each user .. the history can be n+1. Some users have 100's of UserHistory records.

So, can I restrict the the number of UserHistory records to .. 10 or 5 or whatever?

Do I need to use projections for this? Can it be done without projections?


Solution

  • You can't do this by using the include, but you can try this:

    var query =
        from user in Users
        select new
        {
            user, 
            history = user.UserHistory.Take(20) 
        };
    

    I'm not sure whether EF is able to create one single SQL query of of it.