EF: Include with where clause

前端 未结 4 1427
执念已碎
执念已碎 2020-11-21 07:45

As the title suggest I am looking for a way to do a where clause in combination with an include.

Here is my situations: I am responsible for the support of a large a

4条回答
  •  [愿得一人]
    2020-11-21 08:48

    In my case the Include was an ICollection, and also did not want to return them, I just needed to get the main entities but filtered by the referenced entity. (in other words, Included entity), what I ended up doing is this. This will return list of Initiatives but filtered by InitiativeYears

    return await _context.Initiatives
                    .Where(x => x.InitiativeYears
                        .Any(y => y.Year == 2020 && y.InitiativeId == x.Id))
                    .ToListAsync();
    

    Here the Initiatives and the InitiativeYears has following relationship.

    public class Initiative
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public ICollection InitiativeYears { get; set; }
    }
    
    public class InitiativeYear
    {
        public int Year { get; set; }
        public int InitiativeId { get; set; }
        public Initiative Initiative { get; set; }
    }
    

提交回复
热议问题