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
With NH 4 (and probably a bit earlier), a built-in Like
string extension is available within NHibernate.Linq
namespace: Like(this string matchExpression, string sqlLikePattern)
. (It is defined on NHibernate.Linq.SqlMethods extension class.)
using NHibernate.Linq;
...
session.Query<Theater>()
.Where(t => t.Name.Like("test"));
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.
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%'
Whilst this has been marked as resolved, which was correct at the time, may I also note that NHibernate has some extensions now so you can do the following:
Session.QueryOver<MyEntity>()
.Where(x => x.Property.IsLike("something", MatchMode.Anywhere))
.List();
This will do a LIKE '%something%'
for you.