C # + Castle ActiveRecord: HasAndBelongsToMany and Collections

Let's say I have a many-to-many relationship (using the ActiveRecord attribute HasAndBelongsToMany) between messages and tags (domain names are changed to protect innocents), and I need a method like

FindAllPostByTags (IList <Tag> tags)
, which returns all messages that have all (and not just some of) the tags in the parameter. Anyway, could I accomplish this with either NHibernate Expressions or HQL? I was looking for HQL documentation and could not find anything to fit my needs. Hope I just missed something obvious!
+3
source share
3 answers

You can also just use the operator IN

DetachedCriteria query = DetachedCriteria.For<Post>();
query.CreateCriteria("Post").Add(Expression.In("TagName",  string.Join(",",tags.ToArray()) );

,

+2

Castle, , , .

Junction c = Expression.Conjunction();
foreach(Tag t in tags)
    c = c.Add( Expression.Eq("Tag", t);

return sess.CreateCriteria(typeof(Post)).Add(c).List();
0

I had the same problem and tried to read the HQL documentation, however some functions do not seem to be implemented in NHibernate (e.g. with a keyword)

I got this solution:

select p 
FROM Post p
JOIN p.Tags tag1
JOIN p.Tags tag2
WHERE
    tag1.Id = 1
    tag2.Id = 2

Value, dynamically create HQL using the union for each tag, then make a selection in your WHERE clause. It worked for me. I tried to do the same with DetachedCriteria, but ran into difficulties when trying to join the table several times.

0
source

Source: https://habr.com/ru/post/1697484/


All Articles