Entity Framework query across multiple levels of relationship

风流意气都作罢 提交于 2020-01-03 17:25:54

问题


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?


回答1:


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();



回答2:


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);




回答3:


You could try this:

var temp = from a in AList
           where a.B.All(b => b.C.All(c => c.ID== myParam))
           select a;

notice that AList is a List<A>.




回答4:


There are many ways to do things with LINQ, sometimes I find that if I'm having a hard time trying to come up with a solution that uses a combination of the existing extension methods I will simply write a join (as you would in sql) using LINQ. The join below doesn't require the actual "join on" part because EF will use your existing mappings (navigational properties) to generate the join 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 does auto-fixup of your objects, meaning you could return only A from your method and be able to traverse it to get B and C.



来源:https://stackoverflow.com/questions/5991584/entity-framework-query-across-multiple-levels-of-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!