I am working on a website where a user can add tags to their posted books, much like is currently done for questions on Stack Overflow.
Classes:
Books
{
bookId,
Title
}
Tags
{
Id
Tag
}
BooksTags
{
Id
BookId
TagId
}
Here are few sample records.
Books
BookId Title
113421 A
113422 B
Tags
Id Tag
1 ASP
2 C#
3 CSS
4 VB
5 VB.NET
6 PHP
7 java
8 pascal
BooksTags
Id BookId TagId
1 113421 1
2 113421 2
3 113421 3
4 113421 4
5 113422 1
6 113422 4
7 113422 8
Questions
-
I need to write something in LINQ to entity queries which gives me data according to the tags:
Query:
bookIds where tagid = 1
Returns:bookid: 113421, 113422Query 2:
tags 1 and 2
Returns:113421 -
I need tags and their count to to show in related tags, so in first case
my related tags class should have following result.RelatedTags
Tag Count
2 1
3 1
4 2
8 1
Second Case:
RelatedTags
Tag Count
3 1
4 1
How do I do this in LINQ?
On the first part, the interesting restriction is that the book has to match every tag entered, so a where clause of “where tagid == someId” wouldn’t really work. I envision something like this (LINQ-to-objects example)
Which basically performs a join from books to booktags and also to the list of selected tag ids and restricts the selection to where the count of book->tag matches equals the count of selected tag ids.
To pull the related tags, maybe something like this
Full code for the quick example. Not fully OOP, but you get the idea.
So for selected tags 1 & 2, you’ll get book A, and the related tags would be 3 (CSS) and 4 (VB).