简体   繁体   中英

LINQ Projected Filtering C#

I want to filter my LINQ query based on an included table but am having some trouble.

Here is the original statement, which works:

return 
    this.ObjectContext.People.
        Include("Careers").
        Include("Careers.Titles").
        Include("Careers.Titles.Salaries");

Now I'm trying to filter on Careers using projected filtering but am having trouble. It compiles but it leaves out the Titles and Salaries tables, which causes runtime errors, and I can't seem to add those tables back in:

var query1 = (
    from c in 
    this.ObjectContext.People.
        Include("Careers").
        Include("Careers.Titles").
        Include("Careers.Titles.Salaries")
    select new
    {
        c,
        Careers = from Careers in c.Careers
                  where Careers.IsActive == true
                  select Careers
    });

    var query = query1.AsEnumerable().Select(m => m.c);
    return query.AsQueryable();

How can I include the titles and salaries tables in the filtered query?

You can simplify your query considerably, which should resolve your issue. I'm assuming that you want all people with at least 1 active career:

var query = 
    from c in 
    this.ObjectContext.People.
        Include("Careers").
        Include("Careers.Titles").
        Include("Careers.Titles.Salaries")
    where c.Careers.Any(c => c.IsActive);

return query;

I would try something like,

var query = from p in ObjectContext.People
            join c in ObjectContext.Careers on p equals c.Person
            where c.IsActive
            select p;

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