多对多查询实体框架4 [英] Many to Many Query in Entity Framework 4
问题描述
我有一个多对多的关系在我的数据库。两个端表是博文和项目,并在中间表ItemBlogPost。我需要找回所有与特定项目相关博客文章的。在SQL中我会做这样的:
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
在C#中我有类似的东西:
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;
然而,行标b.Items不给我的项目属性的列表,并且没有b.ItemBlogPost看中间表。我也试着做 b.Items.Contains(项目)
但也失败了。我怎样才能使这项工作在LINQ to EF4?
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?
推荐答案
这个是什么:
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);
这篇关于多对多查询实体框架4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!