Is there a way to defined .Where inside .Include

c# entity-framework linq


I have the following model class method:-

public IQueryable<TMSSwitch> AllFindServer_Switches(int id        {

return tms.TMSSwitches.Where(c => c.TMSSwitchPorts.Any(a6=>a6.TechnologyID == id))

.Include(a10 => a10.TMSSwitchPorts.Where(a=>a.TechnologyID==id).Select(a=>a.Technology))
.Include(a11 => a11.TMSServer.Technology)

But I am unable to define .Where inside the .Include, as I need to only include certain records from the navigation property. But the above code will cause the following error on run-time:-

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation propertie

Can anyone advice, if there is a way to have .Where inside .include ? Thanks

11/19/2013 10:04:52 AM

Accepted Answer

It seems you cannot sort the children collection in your query. Either sort after the query or load the children in a second query.

Similar question and answer here

5/23/2017 12:18:17 PM

Popular Answer

The extension method Includeis a mere wrapper around DbQuery.Include. Internally it does not execute the expressions but only parses them, i.e. it takes their member expressions and converts them to a path as string. The path is used as input for DbQuery.Include.

It has been requested before to enhance the functionality of Include, e.g. to allow partly loaded collections by including a Where clause. Ordering could be another change request. But as you see, because of the internal working of Include the whole mechanism will have to be re-engineered to implement such enhancements. I don't see it on the current road map so it may take a while...

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow