简体   繁体   中英

NHibernate QueryOver with Restrictions

I am new to NHibernate and trying to use the QueryOver . I have the following NHibernate query

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

I have a single value to pass into IsIn and for that I have to new up a list ( new List<int> {100} )). Is there a more cleaner way of doing this?

Your syntax is ok, and only few changes or improvements can be done... here they are:

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();

See more: 16.2. Simple Expressions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM