跨多个关系级别的实体框架查询
我刚刚开始学习实体框架和 Linq To Entities,并试图了解查询。
我有一个数据结构如下:
表A、B、C。A
与B具有一对多关系,B与C具有一对多关系。
我们的表示对象之一由来自A、B和C的数据组成。 C 给定 C 的 Id
那么,我如何在查询中表示它呢?
如何从 where c.Id == myParam
查询获取 A 实体?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
大概情况:
其中
B
是C
到B
实例的导航属性,A
是来自C
的导航属性>B 到A
的实例。如果引用了 System.Data.Entity 命名空间,您还可以使用 lambda 表示法:
对于 Collection 导航属性,您可以使用 .Select()
What about:
Where
B
is navigation property onC
to instance ofB
anA
is navigation property fromB
to instance ofA
.You can also use lambda notation if System.Data.Entity namespace is refeneced:
And for Collection navigation properties you can use .Select()
如果您确保加载对象 A 的所有引用以便您可以访问它们,则以下内容有效。
var C= lstA.Where(p => pBFirstOrDefault().C == cID);
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);
您可以尝试以下操作:
注意
AList
是一个List
。You could try this:
notice that
AList
is aList<A>
.使用 LINQ 做事的方法有很多,有时我发现,如果我很难想出一个使用现有扩展方法组合的解决方案,我会简单地编写一个连接(就像在 sql 中一样) )使用 LINQ。下面的联接不需要实际的“联接”部分,因为 EF 将使用您现有的映射(导航属性)为您生成联接。
从这里您将拥有一个匿名类型,其中包含来自所有三个表的数据。最好的部分是 EF 会自动修复您的对象,这意味着您可以从方法中仅返回 A,并能够遍历它以获取 B 和 C。
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.
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.