[英]Many to Many Query in Entity Framework 4
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.
两个结束表是BlogPost和Item,中间的表是ItemBlogPost。 I need to get back all of the BlogPosts related to a specific item.
我需要找回与特定项目相关的所有BlogPost。 In SQL I would do it like this:
在SQL中,我会这样做:
SELECT BlogPost.*
FROM BlogPost
JOIN ItemBlogPost ON BlogPost.ID = ItemBlogPost.BlogPost_ID
WHERE ItemBlogPost.Item_ID = @Item_ID
In C# I have something similar: 在C#中我有类似的东西:
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. 但是,标记为b.Items的行没有给出Item属性的列表,并且没有b.ItemBlogPost来查看中间表。 I also tried doing
b.Items.Contains(item)
but that also failed. 我也尝试过做
b.Items.Contains(item)
但也失败了。 How can I make this work in LINQ to EF4? 如何在LINQ to EF4中完成这项工作?
What about this: 那这个呢:
var itemBlogPosts = from i in connection.Items
from b in i.BlogPosts // I suppose you have a nav. property on Item
where i.Id == itemId
select b;
The same query can be also defined by: 同样的查询也可以通过以下方式定义:
var itemBlogPosts = connection.Items
.Where(i => i.Id == itemId)
.SelectMany(i => i.BlogPosts);
Can you just do this: 你能做到这一点:
var itemBlogPosts = connection.Items.Single(b => b.ID == item.ID).BlogPosts;
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. 由于您使用EF,它应该为您处理多对多映射,您应该将BlogPosts作为项目对象中的导航项。
If: 如果:
Then: 然后:
This way: 这条路:
So when you have your specific item by hand you can just create a collection of related blogposts by doing: 因此,当您手动拥有特定项目时,您可以通过以下方式创建相关博客帖子的集合:
Item item = context.Items.Include("BlogPosts").FirstOrDefault<Item>(i => i.ID = someID)
Now you have a specific item with the collection of blogposts filled (if any were related to this item). 现在您有一个特定的项目,其中填充了博客帖子(如果有任何与此项目相关)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.