Nhibernate + QueryOver: filter with Where ignoring sensitive

后端 未结 5 1220
一生所求
一生所求 2021-01-11 22:54

I am trying to build a simple query in nHibernate with QueryOver but I want it to convert everything lower-case or ignore sensitive:

Domain.User User = Sessi         


        
相关标签:
5条回答
  • 2021-01-11 23:23
    public static class QueryOverExtension
    {
        /// <summary>
        /// This method is used in cases where the root type is required
        /// Example: .WhereEqualInsensitive(t => t.Property, stringValue)
        /// </summary>
        public static IQueryOver<T, TU> WhereEqualInsensitive<T, TU>(this IQueryOver<T, TU> queryOver, Expression<Func<T, object>> path, string value)
        {
            return queryOver.Where(Restrictions.Eq(Projections.SqlFunction("upper", NHibernateUtil.String, Projections.Property(path)), value.ToUpper()));
        }
    
        /// <summary>
        /// This method is used in cases where the root type is NOT required
        /// Example: .WhereEqualInsensitive(() => addressAlias.DefaultEmail, contactEmailAddress)
        /// </summary>
        public static IQueryOver<T, TU> WhereEqualInsensitive<T,TU>(this IQueryOver<T, TU> queryOver, Expression<Func<object>> path, string value)
        {
            return queryOver.Where(Restrictions.Eq(Projections.SqlFunction("upper", NHibernateUtil.String, Projections.Property(path)), value.ToUpper()));
        }
    }
    

    Usages:

    Session.QueryOver<DTO>()
               .WhereEqualInsensitive(t => t.Property, value)
    
    ChildDTO childAlias = null;
    Session.QueryOver<DTO>()
               .JoinAlias(t => t.ChildDTO, () => childAlias)
               .WhereEqualInsensitive(() => myAlias.Property, value)
    
    0 讨论(0)
  • 2021-01-11 23:24

    NH 3.0 has a linq provider so you can use

    Session.Query<Domain.User>()
               .Where(x=>x.Login.ToLower() =="username")
               .SingleOrDefault();
    
    0 讨论(0)
  • 2021-01-11 23:26

    In QueryOver you can use following:

    Domain.User User = Session.QueryOver<Domain.User>()
           .WhereRestrictionOn(x=>x.Login).IsInsensitiveLike("username")
           .SingleOrDefault();
    
    0 讨论(0)
  • 2021-01-11 23:42

    my workaround for this is using a expression.eq combined with a projection, so a case insensitive equals without any magic strings can be done with queryover

    query.Where(Expression.Eq(Projections.Property(Of MyType)
                    (Function(x) x.Name), "something").IgnoreCase)
    
    0 讨论(0)
  • 2021-01-11 23:42

    Better way is to change collation of your database to case insensitive one. If you can change database.

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