Entity Framework Request at Different Relationship Levels

I'm just starting out in the Entity Framework and Linq To Entities, and I'm trying to figure out the query.

I have a data structure as follows:

Tables A, B, C.

A relates from one to many to B, B relates to one to many to C.

One of our view objects consists of data from A, B and C given by Id from C

So how can I present this in a query?

How to get object A from a query where c.Id == myParam ?

+4
source share
4 answers

What about:

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

Where B is the navigation property in C for instance B a A is the navigation property from B to instance A

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

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

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

 var c = context.Cs.Include(i=>i.Select(j=>jA)).Where(c => c.Id == myParam).SingleOrDefault(); 
+4
source

below works if you make sure that all references to object A are loaded so that you can access them.

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

+3
source

You can try the following:

 var temp = from a in AList where aBAll(b => bCAll(c => c.ID== myParam)) select a; 

note that AList is a List<A> .

+2
source

There are many ways to do something with LINQ, sometimes I find that if I find it difficult to find a solution using a combination of existing extension methods, I will simply write a connection (since you will be in sql) using LINQ. Joining below does not require the actual β€œjoin on” part, because EF will use your existing mappings (navigation properties) to create the junction for you.

 var query = from a in Ta from b in Tb from c in Tc where C.Id == myParam select new { A = a, B = b, C = c}; 

From here you have an anonymous type that has data from all three tables. The best part is that EF will automatically commit your objects, which means that you can only return A from your method and be able to traverse it to get B and C.

0
source

All Articles