views:

608

answers:

2

How can I produce this query using NHibernate.Linq?

WHERE this_.Name LIKE @p0; @p0 = 'test'  // Notice NO % wild card

Note, this is not Linq To Sql or Entity Framework. This is NHibernate.

Edit:

Here is the desired query using ICriteria:

criteria.Add(Expression.Like("Name", "test"));
return criteria.List<Theater>();
+1  A: 

I believe this is what you are looking for:

var theaters = from theater in Session.Linq<Theater>() 
               where theater.Name.Contains("test") 
               select theater;

According to my tests it generates an SQL 'LIKE' statement: "... WHERE theater.Name LIKE %test%"

which is exactly the output of the criteria snippet you have provided.

tolism7
Using Criteria (provided in the question), I am not seeing the % wildcards being generated.
mxmissile
I have just ran the unit test that I have with the code provided in my answer and it produced a SQL statement with the % wildcard in both ends on the serch string.I also run the same test using the Criteria equilevant and I get the exact same SQL statement if I use criteria.Add(Expression.Like("Name", "test", MatchMode.Anywhere));I use NHibernate 2.1 with SQL Server 2005.If you are using the same configuration then you should be able to see the same results.
tolism7
The issue is I don't want the wildcards using Linq. My comment above this was responding to your answer "exactly the output of the criteria snippet you have provided". Sorry if I was not clear. I can achieve the desired query with ICriteria as stated in the Question, but cannot seem to achieve it using Linq.
mxmissile
So you want to generate a LIKE statment WITHOUT the % around your search string. As you say you are doing that already with Criteria but you want to achieve the same with LINQ. I apologise for misreading your initial comment... Can I ask why would someone want to do that? I believe the LIKE operator without wildcards is the same or at least is optimised to be the same as using the '=' operator.
tolism7
Yes, that is my question. The reason why is given the criteria LIKE 'test' returns values with 'TEST' and not 'TESTEST'. Or in other words 'Test' != 'test'. So basically its for ignoring case only. Hope that makes sense.
mxmissile
+1  A: 

I had the same problem in my project and found a solution :

session.Linq<Theater>()
    .Where(x => x.Name.StartsWith("test") && x.Name.EndsWith("test");

This translates in SQL to

SELECT ... WHERE Name LIKE '%test' AND Name LIKE 'test%'
CMerat