开发者

Nhibernate linq. The where extension method does not add the where clause to the SQL command, why?

开发者 https://www.devze.com 2023-02-10 10:48 出处:网络
I want to add the where clause to a linq statement, but it doesn\'t behave as i would expected it to.

I want to add the where clause to a linq statement, but it doesn't behave as i would expected it to. When i use this code:

IQueryable<Employee> EmpQuery = from e in Session.Query<Employee>() where e.Surname == "Test" select e;
        EmpQuery.ToList();

or i use this code:

IQueryable<Employee> EmpQuery = (from e in Session.Query<Employee>() select e).Where(e => e.Surname == "Test");
        EmpQuery.ToList();

The where clause is included in the SQL com开发者_开发技巧mand, but when i try it this way:

IQueryable<Employee> EmpQuery = from e in Session.Query<Employee>() select e;
        EmpQuery.Where(e => e.Surname == "Test");

The where clause is not included in the SQL command. Why is this? Is there another way to dynamically add criteria to a Nhibernate Linq query?


You're not using the return value of Where. LINQ is designed around functional concepts - calling Where doesn't modify the existing query, it returns a new query which applies the filter. The existing query remains as it was - which means you can reuse it for (say) a different filter.

Note that your current query expression (from x in y select x, effectively) is pretty pointless. I would suggest simply writing:

var query = Session.Query<Employee>().Where(e => e.Surname == "Test");


Just to clarify on Jon's remark, your implementation would be fine with the following tweak:

IQueryable<Employee> modifiedQuery = EmpQuery.Where(e => e.Surname == "Test");

Then just invoke the appropriate enumerator (ToList, ToArray, foreach) on modifiedQuery. And I wouldn't say that it create a complete new query, but instead creates a query which wraps around the original (kind of along the lines of the adapter pattern). Granted, your example doesn't need the additions, but this is how you would add additional criteria onto an existing LINQ expression, and that is what your question actually asked.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号