简体   繁体   中英

How to filter specific columns from a child table Entity Framework

I have 3 tables with 1:many parent child relation

  • TableA
  • TableB (child of TableA)
  • TableC (child of TableB)

I am able to retrieve all of the data from these tables with query

var data = dbContext.tableA.where(a => a.ID == rowID)
           .Include(a => a.tableB.Select(n => n.tableC)).SingleOrDefault();

For TableC , I don't want all of the columns to be retrieved from database. I just want ID, TableC_FK columns data to be retrieved for TableC .

How do I do that?

I think you cannot project into TableA unless you have scheme that support it. IMHO The best option is either anonymous project or Use Viewmodel/DTO suggested by @jpgrassi

You can use anonymous here, more tutorial of anonymous projection here

var data = dbContext.tableA
                    .where(a => a.ID == rowID)
                    .Select(tableA=> new 
                    {
                       firstColumn = tableA.FirstColumn,
                       tableC = tableA.SelectMany(tableB=>tableB.TableC),
                    }.SingleOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM