Tricky situation with EF and Include while projecting (Select / SelectMany)

Posted by Vincent Grondin on Geeks with Blogs See other posts from Geeks with Blogs or by Vincent Grondin
Published on Sat, 07 Jun 2014 09:27:09 GMT Indexed on 2014/06/07 21:26 UTC
Read the original article Hit count: 202

Filed under:

Originally posted on: http://geekswithblogs.net/vincentgrondin/archive/2014/06/07/tricky-situation-with-ef-and-include-while-projecting-select.aspx

Hello,

the other day I stumbled on a problem I had a while back with EF and Include method calls and decided this was it and I was going to blog about it…  This would sort of to pin it inside my head and maybe help others too !  So I was using DBContext and wanted to query a DBSet and include some of it’s associations and in the end, do a projection to get a list of Ids…   At first it seems easy…  Query your DBSet, call Include right afterward, then code the rest of your statement with the appropriate where clause and then, do the projection…   Well it wasn’t that easy as my query required I code my where on some entities a few degree further in the association chain and most of these links where “Many”…  I had to do my projection right away with the SelectMany method.  So I did my stuff and tested the query….  no association where loaded…  My Include statement was simply ignored !  Then I remembered this behavior and how to get it to work…  You need to move the Include AFTER your first projection (Select or SelectMany).  So my sequence became:   Query the DBSet, do the projection with SelectMany, Include the associations, code the where clause and do the final projection…. but it wouldn’t compile…   It kept saying that it could not find an “Include” method on an IQueryable… which is perfectly true!  I knew this should work so I went to the definition of the DBset and saw it inherited DBQuery and sure enough the include method was there…  So I had to cast my statement from start until the end of the first projection in a DBQuery then do the Includes and then the rest of my query….   Bottom line is, whenever your Include statement seem to be ignored, then maybe you will need to move them further down in your query and cast your statement in whatever class gives you access to the Include…

 

Happy coding all !

© Geeks with Blogs or respective owner