2014-08-30 23 views
3

我想在SELECT子句中Concat的员工名字和姓氏,但它给:如何Concat的两个列与Hibernate queryover使用LINQ

无法从新<> f__AnonymousType0`1(名称= 格式确定成员( “{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>(); 
+0

'string.Format'有很多不同的选项,对于大多数SQL引擎太复杂完成尝试使用'x.FirstName +“”+ x.LastName' – Matthew 2014-08-30 14:11:50

+0

我刚刚尝试过你的建议,但它仍然给出了相同的错误 – semirturgay 2014-08-30 14:14:17

+0

也有可能是查询引擎无法理解匿名类型的'new {name = string。格式(“{0} {1}”,x.FirstName,x.LastName)}'。我不熟悉fluent-nhibernate,但也许你可以直接使用字符串'string.Format(“{0} {1}”,x.FirstName,x.LastName)'?它将如何与下面的“WithAlias”进行互操作,我不知道,但是,这是一个合理的猜测。 – 2014-08-30 14:16:38

回答

5

QueryOver的语法将看起来像这样:

// 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) 

我们从sql函数中获利concat。我们通过一个Projections.SqlFunctionSelect()语句和使用一些默认/基本建立部分Projections

+0

你很棒:)感谢您的关注.. – semirturgay 2014-08-30 14:28:04

+0

NHibernate很棒!享受它;) – 2014-08-30 14:28:23

+0

实体永远。:)老板让我使用NHibernate:/ – semirturgay 2014-08-30 14:30:12

4

还是现在更简单:

using NHibernate.Criterion; 

SelectList(l => l 
    .Select(x => Projections.Concat(m.FirstName, ", ", m.LastName)) 
    .WithAlias(() => businessSectorItem.text)) 
)