NHibernate.Linq LIKE

前端 未结 4 1320
眼角桃花
眼角桃花 2021-02-12 10:02

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

相关标签:
4条回答
  • 2021-02-12 10:16

    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"));
    
    0 讨论(0)
  • 2021-02-12 10:26

    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.

    0 讨论(0)
  • 2021-02-12 10:28

    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%'
    
    0 讨论(0)
  • 2021-02-12 10:33

    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.

    0 讨论(0)
提交回复
热议问题