Search code examples
c#linqentity-framework-core

In One To Many Relationship, How Do I Return JUST The Many entities Given A Specific Entity On The One Side


I have two two tables A and B that have a one to many relationship. I want to return all the B records (as a list) associated with the most recent A record that has a specific UserId. I have the following LINQ statement but it's only returning the first of the B entities (assuming it's the FirstOrDefaultAsync, just not sure what to replace it with) instead of all of the B records as a list associated with the given A record. I had another LINQ query that worked but it made two DB calls, so I was given this to make it one DB call (good thing I tested it). I'm sure it's a very basic thing I'm missing here I'm just spinning my wheels at this point:

var test = await _db.RecordA
.Where(A=> A.UserId == 1) //A UserId can be associated with multiple A records
.OrderByDescending(A => A.DateGenerated)
.Take(1) //I want the most recent A record
.Select(A => A.RecordB.ToList()) //There could be many B records associated with the given A record, hence the lazy loading
.FirstOrDefaultAsync();

Solution

  • Would this work? I added .Include() and .SelectMany()

    var test = await _db.RecordA
                        .Include(A => A.RecordB)
                        .Where(A => A.UserId == 1)
                        .OrderByDescending(A => A.DateGenerated)
                        .Take(1)
                        .SelectMany(A => A.RecordB)
                        .ToListAsync();