Fluent NHibernate - Filtering resultset

2019-09-08 21:58发布

FNH Newbie question -

I have two objects RR and TT defined as following:

public class RR
{
   Id
   Name
   TT_Id //corresponds to TT.Id
}

public class TT
{
   Id
   Name
   Type   
}

I want to filter records from RR as per following SQL:

SELECT RR.*
FROM RR 
LEFT OUTER JOIN TT ON RR.TT_Id = TT.Id
WHERE TT.Type <> 7 

Can anyone please guide how can I add filter criteria to achieve above in NH.

Thank you!

1条回答
乱世女痞
2楼-- · 2019-09-08 22:25

why you have TT_Id and not TT itself in RR? IMO it will make a lot of things more difficult than needed.

if it would reference to TT then

resultlist = session.CreateCriteria<RR>()
    .CreateCriteria("TT")
    .Add(Restrictions.Not(Restrictions.Eq("Type", 7)))
    .List<RR>();

otherwise

var subquery = DetachedCriteria.For<TT>()
    .Add(Restrictions.Not(Restrictions.Eq("Type", 7)))
    .SetProjection(Projections.Id());

resultlist = session.CreateCriteria<RR>()
    .Add(Subqueries.In("TT_id", subquery)))
    .List<RR>();

or

IList<object[]> resultlist = session.CreateSqlQuery("SELECT RR.* FROM RR LEFT OUTER JOIN TT ON R.TT_Id = TT.Id WHERE TT.Type <> 7 ")
    .List().Cast<object[]>();

// hydrate RR yourself here
查看更多
登录 后发表回答