Entity Framework 4.0 2 具有相同实体的多对多
我有 2 个实体(例如 People
和 Books
),它们具有两个多对多关系。我创建了两个不同的链接表 - 例如,链接表称为 BooksCheckedOutByPeople
和 BooksOnHoldByPeople
。
EF 4.0 正确地建立了两种关系。它称它们为 PeopleBooks
和 PeopleBooks1
。
当我进行 Linq 查询时,如何告诉 Linq 使用这些关系中的特定一种? Linq 有没有办法指定一种关系而不是另一种关系?
假设我正在创建针对 People
的查询,并且想要获取 BooksCheckedOutByPeople
的 Books
,因此我需要使用关系 PeopleBooks
。
谢谢。
I have 2 entities (say People
and Books
) that have two many-to-many relationships. I have created two different linking tables - e.g. the linking tables are called BooksCheckedOutByPeople
and BooksOnHoldByPeople
.
EF 4.0 correctly makes two relationships. It calls them something like PeopleBooks
and PeopleBooks1
.
When I am making Linq queries, how do I tell Linq to use a specific one of these relationships? Is there any way in Linq to specify one relationship instead of the other?
Say I'm creating a query against People
and I want to get the Books
for BooksCheckedOutByPeople
and thus I need to use the relationship PeopleBooks
.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该能够通过编辑 EF 为您生成的模型,将“PeopleBooks”和“PeopleBooks1”重命名为信息更丰富的属性名称。类似于“BooksOnHold”和“BooksCheckedOut”。
此时,在编写 LINQ 查询时,只需引用正确的导航属性(如它们的名称所示)。 LINQ 使用您指定的任何属性,并且实体框架应该为每个集合生成唯一的导航属性。
编辑
我刚刚启动 VS2010 来复制你的模型并浏览一下。
我发现 EF4 确实为 Book 和 Person 生成了两个导航属性,分别称为 People 和 People1、Books 和 Books1。
如果您在模型浏览器中选择任何这些导航属性并查看“属性”窗格,您应该能够看到哪个表与该关联相关,并相应地重命名该属性。这是我的电脑的屏幕截图:
您可以看到我已为“Book”选择了“People”导航属性“ 实体。本例中的关联由 BooksCheckedOutByPeople 确定,因此我可以将该属性重命名为“PeopleCheckingOut”,或者比“People”更有用的名称。当我稍后使用 LINQ-to-Entities 时,我会引用“PeopleCheckingOut”属性来查询任何特定书籍上的该集合。
You should be able to rename "PeopleBooks" and "PeopleBooks1" to more informative property names by editing the model EF generates for you. Something like "BooksOnHold" and "BooksCheckedOut".
At that point, when writing your LINQ queries, just reference the right navigation properties (as they're called). LINQ uses whichever properties you specify, and the Entity Framework should generate a unique navigation property for each collection.
Edit
I just fired up VS2010 to copy your model and poke around a bit.
I see that EF4 did indeed generate two Navigation Properties foor Book and Person, called People and People1, and Books and Books1 (respectively).
If you select any of these Navigation Properties in the Model Browser and look at the Properties pane, you should be able to see which table is correlated to that association and rename the property appropriately. Here's a screenshot from my PC:
You can see that I've selected the "People" nav property for the "Book" entity. The association in this case is determined by BooksCheckedOutByPeople, so I can rename the property to "PeopleCheckingOut", or something more useful than "People". When I'm using LINQ-to-Entities later, I then reference the "PeopleCheckingOut" property to query that collection on any specific Book.