我创建了三个表 - Podcast、Category 和 CategoryLink。CategoryLink 表仅包含两列 - PodcastId 和 CategoryId。如本文所述,我已经描述了这些表之间的多对多关系。一切正常,但我不知道如何正确进行查询。现在我通过以下方式做到这一点:
var ps = db.Podcasts.Where(p => p.Status.SysStatus > 0);
if (category_id.HasValue)
ps = ps.Where(p => p.Categories.Where(c => c.Id == category_id.Value).FirstOrDefault() != null);
它有效,但我认为这有点肮脏:-)
它给了我以下 SQL 查询(我删除了多余的列和字符串):
SELECT
[Project2].[Id] AS [Id]
FROM ( SELECT
[Extent1].[Id] AS [Id],
(SELECT TOP (1)
[Extent3].[CategoryId] AS [CategoryId]
FROM [dbo].[CategoryLink] AS [Extent3]
WHERE ([Extent1].[Id] = [Extent3].[PodcastId]) AND ([Extent3].[CategoryId] = 1)) AS [C1]
FROM [dbo].[Podcast] AS [Extent1]
INNER JOIN [dbo].[PodcastStatus] AS [Extent2] ON [Extent1].[StatusId] = [Extent2].[Id]
WHERE [Extent2].[SysStatus] > 0
) AS [Project2]
WHERE [Project2].[C1] IS NOT NULL
问题是如何进行查询,以便我可以在inner join
没有子查询的情况下获得“正常”?
谢谢。