I’ve created three tables – Podcast, Category and CategoryLink.
The CategoryLink table contains only two columns – PodcastId and CategoryId.
I have described many-to-many relations between these tables as written in this article.
All works fine but I don’t know how to make query correctly.
Now I do this by the following way:
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);
It works, but I think it’s a little dirty way 🙂
It give me the following SQL query (I’ve removed excess columns and strings):
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
The querstion is that how to do query so I can get a ‘normal’ inner join without sub-queries?
Thanks.
I am not sure what you’re trying to accomplish. Many-to-Many is not much different from Many-to-One in the object mapping, except that you can access the relationship from both sides:
Depending on what you try to accomplish you might also want to do something like this:
If you’re new to LINQ I recommend taking a look at LinqPad. It includes quite a few examples that should give you an idea on how it works.
Update:
Could you maybe elaborate what you actually want to get?
The select in my second example can also be done without a
PurchaseItemsclass: