使用 Entity Framework 和 .NET 3.5 查询多对多关系
我的问题实际上有两个方面。首先,我对 EF 还很陌生,但我通过之前的捷径使用它并取得了一些成功。不过,对于这个特定的项目,我计划花时间学习。
我现在拥有的是一个非常简单的数据库结构:
Post
===================
Id Title
-------------------
1 Hello world
2 Foo bar baz
Tag
===================
Id Title
-------------------
6 test
7 todo
PostTags
===================
PostId TagId
-------------------
1 6
1 7
2 7
使用 EF,它生成一个具有两个实体的模型:Post 和 Tag。
我想要完成的任务:
我试图在给定 tagId 数组(例如 6 和 7)的情况下查询所有帖子的模型。但是我不知道我需要做什么才能使其发挥作用。 以前,我曾通过将自动增量 PK 添加到映射表 (BlogPosts) 并将其添加到 EF 模型中的方式进行作弊,但为了继续前进,这更像是一个丑陋的黑客行为。这次我宁愿学习如何正确地做这件事。
My problem is actually two-fold. First, I'm pretty new to EF but I've used it with some success by taking shortcuts earlier. Though, for this particular project I plan to take the time to learn.
What I have at this point is a very simplistic database structure:
Post
===================
Id Title
-------------------
1 Hello world
2 Foo bar baz
Tag
===================
Id Title
-------------------
6 test
7 todo
PostTags
===================
PostId TagId
-------------------
1 6
1 7
2 7
Using EF, it generates a model with two entities: Post and Tag.
What I'm trying to accomplish:
I'm attempting to query the model for all posts given an array of tagIds (6 and 7 for instance). However I can't figure out what I need to do to make that work.
Previously I've cheated in the way that I added an auto-incremental PK to the mapping table (BlogPosts) and added it into the EF-model but it was more of an ugly hack in order to move forward. I'd rather learn how to do it right this time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这将在 EFv4 中起作用。在 EFv1 中尝试一下:
编辑:
我检查了它,并在 EFv4 中添加了集合值参数 +
Contains
,因此上面的示例在 EFv1 中不起作用。 MSDN 论坛中的此帖子< /a> 提供了允许在 EFv1 中使用 IN 运算符的解决方法。另一个建议的解决方法是升级到 EFv4,因为还有许多其他改进,包括性能的显着改进。This will work in EFv4. Try it in EFv1:
Edit:
I checked it and collection valued parameters +
Contains
were added in EFv4 so above example doesn't work in EFv1. This thread in MSDN forum provides workaround to allow IN operator in EFv1. Another recommended workaround is simply upgrade to EFv4 because there are many other improvements including significant improvement of performance.