I'm tearing my hair out on this one...
Suppose we have a list of blogs which have tags assigned to them. The user searches for any term, and the result must include:
- All blogs whose name contains the term OR
- All blogs where any tags name contains the term
- Only the tags whose name matches the term
The SQL-query that achieves this:
declare @query varchar(20) = '%name%';
SELECT *
FROM Blogs blog
INNER join BlogTags bt on blog.ID = bt.BlogId --join table
INNER join Tags tag on tag.Id = bt.TagId
and tag.name like @query -- condition 3
WHERE blog.name like @query -- condition 1
OR tag.name like @query -- condition 2
I've been trying all day to make this work in an NHibernate query, but I'm always stuck on the OR condition since they don't refer to the same object.
Using Restrictions.Like
doesn't seem to understand that I want a nested property and filtering a nested object is typically done using CreateCriteria
which is not available inside a Restrictions.Or
.
I also haven't found a way to incorporate condition 3.
I don't really care if it's done using Query
, QueryOver
or CreateCriteria
. Currently, I just want it to work :)
Possibly relevant other SO questions:
- Filtering children
- Answer:
Session.CreateCriteria<Parent>().CreateCriteria("Children").Add(/*...*/)
- Answer:
- Restrictions.Or
- String.Contains in NHibernate
- Answer:
Session.QueryOver<Blog>().WhereRestrictionOn(c => c.Name).IsLike("")
- Answer: