Ray
Ray

Reputation: 325

How to get a child nested list within a record using EFCore Linq

I have 3 Tables 1.Books 2.PO 3.Books_PO. I would like to pull a single PO record using books_po ref table but I want a list of books within that record.

 Books                    PO                 books_PO
ID   Name             ID    ponumber       poId    bookId
1    book1            3     1234           3       2
2    book2            5     2323           3       3
3    book3

My current query only brings back one book when I need a list of 2 books. If I return .ToList() I get 2 records for the PO but still one book. I am curious to know what I'm trying to do is possible?

ctx.books_po.Where(a => a.po.Id == 3).Include(b => b.Books).FirstorDefault();

Upvotes: 1

Views: 183

Answers (2)

tgralex
tgralex

Reputation: 814

I think you are looking for GroupBy

var singleRecord = ctx.books_po
.Where(a => a.po.Id == 3)
.Include(b => b.Books)
.GroupBy(a => a.po, a => a.Books).FirstOrDefault();

You will get a single record with two fields singleRecord.Key and singleRecord.ToList() will be all the bookIds under that po (== 3)

Upvotes: 1

Satanusse
Satanusse

Reputation: 1

Why not using Books dbContexts instead of book_po ?

ctx.Books.Where(x => x.books_po.poId == 3).ToList();

Upvotes: 0

Related Questions