Search code examples
c#stringnhibernatecontainslinq-to-nhibernate

C# check string contain a word with underscores


I want to get all items which contain "_AT_" or "PV_", but d.Nom.Contains($"PV_") and d.Nom.Contains($"_AT_") gets also items containing only "AT" and "PV"

 IQueryable<DocumentMetadata> docPV = NHibernateSession.Current.Query<DocumentMetadata>()
           .Where(d => d.IdEntiteRattachement == missionId
                       && d.Nom.Contains($"PV_")
                       && d.Desactive == false)
           .OrderByDescending(d => d.DateDerniereModif);

        IList<DocumentMetadata> docAR = NHibernateSession.Current.Query<DocumentMetadata>()
           .Where(d => d.IdEntiteRattachement == missionId
                       && d.Nom.Contains($"_AT_")
                       && d.Desactive == false)
           .OrderByDescending(d => d.DateDerniereModif).ToList();

Solution

  • In SQL, underscore (and percent) are wild cards. NHibernate doesn't automatically escape them, because you can make use of them. Behind .Contains, there is SQL's LIKE.

    Escaping wildcards depend on the underlying DBMS.

    Try this:

    d.Nom.Contains("\\_AT\\_")
    

    (It may not work. See the docs of your database engine.)