Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework query across multiple levels of relationship

I'm just beginning in Entity Framework and Linq To Entities and am trying to get my head around querying.

I have a data structure as follows:

Tables A, B, C.

A has one to many relationship to B, B has one to many relationship to C.

One of our presentation objects is composed of data from A, B & C given the Id from C

So, how can I represent this in a query?

How do I get an A entity from a where c.Id == myParam query?

like image 870
Shevek Avatar asked Jan 19 '23 18:01

Shevek


2 Answers

What about:

var c = context.Cs.Include("B.A").Where(c => c.Id == myParam).SingleOrDefault();

Where B is navigation property on C to instance of B an A is navigation property from B to instance of A.

You can also use lambda notation if System.Data.Entity namespace is refeneced:

var c = context.Cs.Include(i=>i.B.A).Where(c => c.Id == myParam).SingleOrDefault();

And for Collection navigation properties you can use .Select()

var c = context.Cs.Include(i=>i.Select(j=>j.A)).Where(c => c.Id == myParam).SingleOrDefault();
like image 51
Ladislav Mrnka Avatar answered May 10 '23 17:05

Ladislav Mrnka


the below works if you are making sure that all references of object A are loaded so you can access them.

var C= lstA.Where(p => p.B.FirstOrDefault().C == cID);

like image 28
Saber Shebly Avatar answered May 10 '23 19:05

Saber Shebly