具有限制的NHibernate QueryOver

时间:2014-07-07 03:03:15

标签: c# nhibernate linq-to-nhibernate queryover

我是NHibernate的新手并尝试使用QueryOver。我有以下NHibernate查询

var departments = session
   .QueryOver<Department>()
   .Where(Restrictions.On<Department>x=> x.Parent.Id).IsIn(new List<int> {100}))
   .List().ToList();

我有一个值传递给IsIn,为此我必须新建一个列表(new List<int> {100}))。有更清洁的方法吗?

1 个答案:

答案 0 :(得分:3)

您的语法还可以,只需进行一些更改或改进......这里是:

IList<Department> departments;
var parents = new List<int> {167};

// advantage of this "original" QueryOver is, that it can accept
// more parent IDs.. not only one "100" as in our example
// so if we neet children of 100,101,102
// we can get more from this syntax: new List<int> {100, 101,102...};
departments = session
    .QueryOver<Department>()
    .Where(Restrictions.On<Department>( x=> x.Parent.Id)
        .IsIn(parents))
    .List();

// this style is just a bit more straightforward 
// saving few chars of code, using 'WhereRestrictionOn'
departments = session
    .QueryOver<Department>()
    .WhereRestrictionOn(x => x.Parent.Id).IsIn(parents)
    .List();

// in case we do have the only one parent ID to search for
// we do not have to use the IS IN
departments = session
    .QueryOver<Department>()
    .Where(x => x.Parent.Id == 100)
    .List();

查看更多:16.2. Simple Expressions