NHibernate多对多标准

时间:2010-12-10 10:11:18

标签: sql .net nhibernate icriteria

我有一个问题列表,每个问题都链接到一个标记列表。

以下数据:

Question1 : Tag1
Question2 : Tag1, Tag2
Question3 : Tag1, Tag2, Tag3
Question4 : Tag1, Tag3

以下标准:

var tagsIds = new int[] { tag1, tag2 };

var res = session.CreateCriteria<Question>()
    .CreateCriteria( "Tags" )
    .Add( Restrictions.In( "id", tagsIds ) )
    .List<Question>();

返回(我理解为什么,“in”就像一个OR)

Question1, Question2, Question3, Question4

或者我只想获得

Question2, Question3

因为它们都有tag1 AND tag2。 我有办法做到吗?

在SQL中,我会做类似的事情:

SELECT *
FROM Question q
WHERE EXISTS (
    SELECT *
    FROM QuestionsToTags qtt
    WHERE qtt.Question_id = q.Id
    AND qtt.Tag_id IN ( 1, 2 )
    GROUP BY qtt.Question_id
    HAVING COUNT( qtt.Question_id ) >= 2 
)

2 个答案:

答案 0 :(得分:1)

如果你只有两个,那么使用And限制

var res = session.CreateCriteria<Question>()
    .CreateCriteria( "Tags" )
    .Add( Restrictions.And(Restrictions.Eq("id", tag1), Restrictions.Eq("id", tag2))
    .List<Question>();

如果您有两个以上或未知的数字,请使用Conjunction:

var conj = new Conjunction();
// use a loop to add all tags if number is unknown
conj.Add(Restrictions.Eq("id", tag1);
conj.Add(Restrictions.Eq("id", tag2);

var res = session.CreateCriteria<Question>()
    .CreateCriteria( "Tags" )
    .Add(conj)
    .List<Question>();

还有一个Disjunction类来处理多个Or条件。

答案 1 :(得分:0)

使用hql:

var q = NHibernateSession.CreateQuery(
@"from Question question 
    where exists( 
        select q.id from Question q
        join q.Tags t
        where 
            t.id in (:ids)
            and q.id = question.id
        group by q.id
        having count(t.id)=:c_count )");

q.SetParameterList("ids", tagIds);
q.SetInt32("c_count", tagIds.Length);

使用ICriteria:

// here is the exists part
var dCriteria = DetachedCriteria.For<Question>("q")
    .SetProjection(Projections.GroupProperty(Projections.Id()))
    .Add(Restrictions.Eq(Projections.Count(Projections.Id()), tagIds.Length))
    // here we filter on the "parent" criteria
    .Add(Restrictions.EqProperty("q.id", "question.Id"))
    .CreateCriteria("Tags")
    .Add(Restrictions.In("id", tagIds));

var crit = NHibernateSession
    .CreateCriteria<Question>("question")
    .Add(Subqueries.Exists(dCriteria));