How to include() nested child entity in linq

前端 未结 4 390
日久生厌
日久生厌 2020-12-03 04:17

How do I include a child of a child entitiy?

Ie, Jobs have Quotes which have QuoteItems

var job = db.Jobs
            .Where(x => x.JobID == id)
          


        
相关标签:
4条回答
  • 2020-12-03 04:58

    This will do the job (given that we are talking entity framework and you want to fetch child-entities):

    var job = db.Jobs
                .Include(x => x.Quotes) // include the "Job.Quotes" relation and data
                .Include("Quotes.QuoteItems") // include the "Job.Quotes.QuoteItems" relation with data
                .Where(x => x.JobID == id) // going on the original Job.JobID
                .SingleOrDefault(); // fetches the first hit from db.
    

    For more information about the Include statement have a look at this: http://msdn.microsoft.com/en-us/library/bb738708(v=vs.110).aspx

    This answer has been getting upvotes throught the years, so I'd just like to clarify, try https://stackoverflow.com/a/24120209/691294 first. This answer is for those cases where all else fails and you have to resort to a black magic solution (i.e. using magic strings).

    0 讨论(0)
  • 2020-12-03 05:09

    To get a job and eager load all its quotes and their quoteitems, you write:

    var job = db.Jobs
            .Include(x => x.Quotes.Select(q => q.QuoteItems))
            .Where(x => x.JobID == id)
            .SingleOrDefault();
    

    You might need SelectMany instead of Select if QuoteItems is a collection too.

    Note to others; The strongly typed Include() method is an extension method so you need to include using System.Data.Entity; at the top of your file.

    0 讨论(0)
  • 2020-12-03 05:09

    This did the trick for me as @flindeberg said here . Just added checking if there are children in each parent item in the list

     List<WCF.DAL.Company> companies = dbCtx.Companies.Where(x=>x.CompanyBranches.Count > 0)
                                .Include(c => c.CompanyBranches)
                                .Include("CompanyBranches.Address")
                                .ToList();
    
    0 讨论(0)
  • 2020-12-03 05:10

    The method in the accepted answer doesn't work in .NET Core.

    For anyone using .NET Core, while the magic string way does work, the cleaner way to do it would be ThenInclude:

    var job = db.Jobs
            .Where(x => x.JobID == id)
            .Include(x => x.Quotes)
            .ThenInclude(x => x.QuoteItems)
            .SingleOrDefault();
    

    (source)

    0 讨论(0)
提交回复
热议问题