-1

I'm trying to write an entity framework lambda expression to retrieve the related child data and two related grandchild data from two tables, plus a fourth child table. Here's the relationships.

The parent table is Class. Class has a child table called Course. Course has two child tables, CertificationLevel and CertificationType. The fourth table is called ClassLocation, and is a child table of Class.

I've got to bring in all the related Course, CertificationLevel, CertificationType, and ClassLocation for all the retrieved Class data.

This is what I've currently got:

var recordList = ctx.Classes.OrderByDescending(r => r.ID).Include(c => c.Course).Include(cl => cl.ClassLocation).Take(300);

I searched around for help and found this website Include Multiple Levels, but it doesn't work. Here's the line that I'm having trouble with Include(i => i.Invoices.Select(it => it.Items)). When I try to modify my lambda expression, the Select method isn't recognized.

So, what's wrong and how do I correct it?

I'm using EF 6.4.4. We're using .NET 4.5.2

Rod
  • 4,107
  • 12
  • 57
  • 81

2 Answers2

0

In EF Core I would do something like this(not sure if it is of any help on EF 6.4.4):

var data = context.Class
                    .Include(c => c.Course)
                    .ThenInclude(c => c.CertificationLevel ))
                    .Include(c => c.Course)
                    .ThenInclude(c => c.CertificationType))
                    .Include(c=> c.ClassLocation)
                    .ToList();

This Select isn't recognized? That's strange. I never worked with EF6.0 but every information points it should work https://learn.microsoft.com/en-us/ef/ef6/querying/related-data

recordList = ctx.Classes
                  .OrderByDescending(r => r.ID)
                  .Include(c => c.Course.Select(c=> c.CertificationLevel))
                  .Include(cl => cl.ClassLocation)
                  .Take(300);

There was some solution on the link I posted to use EFCore Style of ThenInclude installing NuGet "Install-Package ThenInclude.EF6". But you shouldn't need to go that far

Henrique Pombo
  • 537
  • 1
  • 6
  • 20
0

Going back to the Include Multiple Levels link I referenced, I thought I'd try the "Using String Path". That worked. So now I have this:

var recordList = ctx.Classes.OrderByDescending(r => r.ID).Include("Course.CertificationType").Include("Course.CertificationLevel").Include("Course.InstrumentModel").Include(cl => cl.ClassLocation).Take(PreselectThreshold);

I would have preferred that the lambda expression would have worked, but it didn't. I do have the System.Data.Entity included, but that made no difference. I'm still wondering if the problem has something to do with the fact that we're using .NET 4.5.2 for development. Anyway, for anyone else struggling with this, try using the string path approach.

Rod
  • 4,107
  • 12
  • 57
  • 81