实体框架 4 中的多对多查询
我的数据库中有多对多关系。两个端表是 BlogPost 和 Item,中间的表是 ItemBlogPost。我需要取回与特定项目相关的所有博客文章。在 SQL 中,我会这样做:
SELECT BlogPost.*
FROM BlogPost
JOIN ItemBlogPost ON BlogPost.ID = ItemBlogPost.BlogPost_ID
WHERE ItemBlogPost.Item_ID = @Item_ID
在 C# 中,我有类似的东西:
IQueryable<BlogPost> itemBlogPosts = from b in connection.BlogPosts
where b.Items == item.ID
orderby b.Content.CreateDate descending
select b;
但是,标记为 b.Items 的行没有给我 Item 属性的列表,并且没有 b.ItemBlogPost 来查看中间表。我也尝试过执行 b.Items.Contains(item)
但也失败了。如何在 LINQ to EF4 中实现此功能?
I have have a many to many relationship in my database. The two end tables are BlogPost and Item and the table in the middle is ItemBlogPost. I need to get back all of the BlogPosts related to a specific item. In SQL I would do it like this:
SELECT BlogPost.*
FROM BlogPost
JOIN ItemBlogPost ON BlogPost.ID = ItemBlogPost.BlogPost_ID
WHERE ItemBlogPost.Item_ID = @Item_ID
In C# I have something similar:
IQueryable<BlogPost> itemBlogPosts = from b in connection.BlogPosts
where b.Items == item.ID
orderby b.Content.CreateDate descending
select b;
However, the line marked b.Items doesn't give me a list of the Item properties and there is no b.ItemBlogPost to look at the intermediary table. I also tried doing b.Items.Contains(item)
but that also failed. How can I make this work in LINQ to EF4?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
怎么样:
同样的查询也可以通过以下方式定义:
What about this:
The same query can be also defined by:
您可以这样做吗:
由于您使用的是 EF,它应该为您处理多对多映射,并且您应该将 BlogPosts 作为 Item 对象中的导航项。
Can you just do this:
Since you are using EF it should handle the many-to-many mapping for you and you should have BlogPosts as a navigation item in your Item Object.
如果:
然后:
这样:
因此,当您手动拥有特定项目时,您可以通过执行以下操作来创建相关博客文章的集合:
现在您拥有一个特定项目,其中填充了博客文章的集合(如果有与该项目相关的内容)。
If:
Then:
This way:
So when you have your specific item by hand you can just create a collection of related blogposts by doing:
Now you have a specific item with the collection of blogposts filled (if any were related to this item).