Search code examples
c#linqnhibernatefluent-nhibernate

how to concat two column with hibernate queryover using linq


I want to concat Employee firstname and lastname at select clause but it gives :

Could not determine member from new <>f__AnonymousType0`1(name = Format("{0} {1}", x.FirstName, x.LastName))

var returnData = UnitOfWork.CurrentSession.QueryOver<Employee>()
                 .OrderBy(x => x.Id).Asc
                 .SelectList(u => u.Select(x => x.Id).WithAlias(() => 
                                           businessSectorItem.id)
                                   .Select(x => new { name = string.Format("{0} {1}",
                                                x.FirstName, x.LastName) })
                                                .WithAlias(() => businessSectorItem.text))
                                   .Where(x => (x.FirstName.IsInsensitiveLike
                                                  ("%" + searchTerm + "%") ||
                                                x.LastName.IsInsensitiveLike
                                                  ("%" + searchTerm + "%")) &&
                                                  ( x.Account == null || x.Account.Id ==
                                                                           accountId))
                                  .TransformUsing(Transformers
                                                  .AliasToBean<SearchEmployeeItemDto>())
                                  .Take(limit)
                                  .List<SearchEmployeeItemDto>();

Solution

  • The QueryOver syntax would look like this:

    // instead of this
    .Select(x => new { name = string.Format("{0} {1}",
         x.FirstName, x.LastName) })
         .WithAlias(() => businessSectorItem.text))                                   
    
    // we should use this
    .Select(
        Projections.SqlFunction("concat", 
            NHibernateUtil.String,
            Projections.Property<Employee>(e => e.FirstName),
            Projections.Constant(" "),
            Projections.Property<Employee>(e => e.LastName)
        )).WithAlias(() => businessSectorItem.text)
    

    We profit here from a sql function concat. We pass a Projections.SqlFunction into Select() statement and build part using some default/basic Projections