简体   繁体   中英

How do you get data across multiple tables with EF and linq?

I have a rather simple db structure, TableA joins to TableB joins to TableC, and I JUST want to get a linq statement to get the populated data objects. Why is it sooooo hard?

I have something like this

TableA
ID (pk)

TableB
ID
TableAID (yes this is a fk to TableA)
TableCID (yes this is a fk to TableC)

TableC
ID (pk)

NOW, I'm trying to do a

var SomeVar = context.Include(t=>t.AnotherTable)
.Include(t => t.YetAnotherTable)
.Include(t => t.TableB)
.Include(t => t.TableC)

or maybe

.Include(t=>t.TableB.TableC)

But when I run these, NOTHING works, errors about navigation props don't exist. How do I get this? Any help would be appreciated please?!

I am not aware of a .Include() method that works on the db context itself, so I might be misunderstanding the question entirely.

It looks like you are thinking in terms of SQL JOIN statements which isn't how the EF works. Let it take care of that for you. Assuming that TableA, TableB, and TableC all have appropriate navigation properties then do something like this:

int myKey = 12345;
TableB myObject = context.TableBs.Where(b => b.ID == myKey).First();

At this point the variable "myObject" is of type TableB and has the properties: ID, TableA, TableB. So if TableA had a property named "Name" you would access that as myObject.TableA.Name. If you want to do this without a round-trip back to the server, you would write this:

TableB myObject = context.TableBs.Include(b => b.TableA).Where(b => b.ID == myKey).First();

This is "eager loading" but it is not necessary for getting data from a related table.

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