Entity Framework Include with condition

后端 未结 4 1265
情歌与酒
情歌与酒 2020-12-11 07:51

I need to filter a dealer based on id and the uncomplete checkins

Initially, it returned the dealer based only on id:

    // TODO: limit checkins to          


        
4条回答
  •  渐次进展
    2020-12-11 08:23

    @Andreas H:

    Awesome, thank you a lot.

    I had to adjust your suggestion like this and it worked:

    var dealer = this.ObjectContext.Dealers
                        .Include("Groups")
                        .Include("Groups.Items")
                        .Include("Groups.Items.Observations")
                        .Include("Groups.Items.Recommendations")
                        .Where(p => p.DealerId == id).
                        FirstOrDefault();
            if (dealer != null)
            {
                this.ObjectContext.Checkins
                        .Include("Inspections")
                        .Include("Inspections.InspectionItems")
                       .Where(c => !c.Complete && c.Dealer.DealerId == dealer.DealerId)
                       .ToList();
            }
            return dealer;
    

    I still have to use the Include otherwise it won't return the referenced entities.

    Note also that Dealer.Groups are unrelated to the Dealer.Checkins.

    So if there's no checkins satisfying the condition, Groups still need to be returned.

    It's interesting to note that at first, I put the two include for checkins to the dealer

    var dealer = this.ObjectContext.Dealers
                            .Include("Groups")
                            .Include("Groups.Items")
                            .Include("Groups.Items.Observations")
                            .Include("Groups.Items.Recommendations")
                            .Include("Checkins.Inspections")
                            .Include("Checkins.Inspections.InspectionItems")
                            .Where(p => p.DealerId == id).
                            FirstOrDefault();
                if (dealer != null)
                {
                    this.ObjectContext.Checkins
                            .Where(c => c.Complete && c.DealerId == id)
                           .ToList();
                }
                return dealer;
    

    but it returned all the Checkins including those which are not complete.

    I don't understand exactly why the latter doesn't work but the former does, how are the entities are resolved. I somehow can intuit that the former returns all data.

提交回复
热议问题