简体   繁体   中英

LINQ include doesn't include related entities when parameters are passed

I have the following code. When I don't give the param "current" and "version" so it only run the first line, the lstFile variable at the end contains the file with it's related jobs. If a give the "current" parameter or the "version" parameter, files are returned without the related Jobs. But since I include the Jobs in the first step, why does the related Jobs are lost in the process?

And by the way, lazy loading is Off, that's why I need to do the include.

IQueryable<File> filteredFiles = entities.Files.Include("Jobs");

if (!String.IsNullOrWhiteSpace(current))
{
    bool bActive = current == "1" ? true : false;

    filteredFiles =
        from f in filteredFiles
        join j in entities.Jobs
            on f.IDFile equals j.IDFile
        where j.Active == bActive
        select f;
}

if (!String.IsNullOrWhiteSpace(version))
{
    filteredFiles =
        from f in filteredFiles
            join j in entities.Jobs
            on f.IDFile equals j.IDFile
        where j.Version == version
        select f;
}

List<File> lstFile = filteredFiles.Distinct().ToList();

The Include merely means that the Jobs property isn't going to defer execution when the query is executed and that each record is going to also return all of the related Jobs records. In your joins you're actually filtering out the files that don't have jobs that meet the given criteria. You aren't filtering out the jobs of those files, you're filtering out all of the files that have those jobs. The Include won't prevent those files from being filtered out.

After Eren Ersönmez point me out that there was an Include function for the IQueryable interface, I decided to try to upgrade my EF4 to EF6 and with this update, the function was available! This is not clear in the documentation from Microsoft.

If that can help someone else, I have followed this tutorial on how to update from EF4 to EF6.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM