1

我正在处理遗留数据,这通常会给我带来分成多列的一个信息。我正在尝试重现以下 SQL 查询...

SELECT * FROM SomeTable WHERE concat(DescriptionPart1,DescriptionPart2) LIKE 'TEST'

...使用 NHibernate QueryOver。所以:

Dim myQuery = Me.Session.QueryOver(Of SomeTable).WhereRestrictionOn( _
    Function(line As SomeTable) line.DescriptionPart1 & line.DescriptionPart2) _
    .IsLike("TEST")

这个自己的语句将遇到以下异常:

Variable 'line' of type 'SomeTable' referenced from scope '', but it is not defined

有什么方向吗?我试图避免使用魔术字符串,但我总是放弃它(因为使用 HQL 连接表达式 + like 函数就像一个魅力)。

4

2 回答 2

1

有点冗长,但它有效

var results = session.QueryOver<SomeTable>()
    .Where(Restrictions.Like(
        Projections.SqlFunction("concat", NHibernateUtil.String, Projections.Property<SomeTable>(x => x.DescriptionPart1), Projections.Property<SomeTable>(x => x.DescriptionPart2)),
        "TEST",
        MatchMode.Anywhere))
    .List();
于 2012-06-11T07:26:59.967 回答
0

作为记录,我使用Linq.

我的问题的要点(我的错,我没有提到)是重用基类中的代码的可能性,所以我想提取给定表的 Description 表达式以将其用于多种目的。最终的想法实现如下:

Public MustInherit Class DefaultBusinessLogic(Of Poco)

  Public Overridable ReadOnly Property DescriptionExpression as Expression(Of Func(Of Poco, String))
    Get
       Return Nothing
    End Get
  End Property

  Public Function SearchByDescription(searchArgument as String) as IEnumerable(Of Poco)
     Dim nhSession as ISession = SessionManager.GetSession()

     Dim query = nhSession.Query(Of Poco)

     If Not String.IsNullOrWhitespace(searchArgument) AndAlso
        Me.DescriptionExpression IsNot Nothing Then

        searchArgument = "%" & searchArgument & "%"        

        Dim isLikeMi = ReflectionHelper.GetMethod(Sub() LinqHelpers.IsLike(Nothing, Nothing)) '* See (1)
        Dim isLikeExpression = Expression.Call(isLikeMi, Me.DescriptionExpression.Body, Expression.Constant(searchArgument))
        Dim whereExpression = Expression.Lambda(Of Func(Of Poco, Boolean))(isLikeExpression, Me.DescriptionExpression.Parameters)
        query = query.Where(whereExpression)
     End If

     Return query.ToList()
  End Function

  Public Function GetDescription(pocoRecord as Poco) as String
     If Me.DescriptionExpression Is Nothing Then Return String.Empty

     Return Me.DescriptionExpression.Compile().Invoke(pocoRecord)
  End Function

End Class

Public Class SomeTableBusinessLogic
   Inherits DefaultBusinessLogic(Of SomeTable)

   Public Overrides ReadOnly Property DescriptionExpression as Expression(Of Func(Of Poco, String))
    Get
       Return Function (row as SomeTable) row.DescriptionPart1 & row.DescriptionPart2
    End Get
  End Property

End Class

Public Class SomeTable

   Public Overridable Property Id as Integer
   Public Overridable DescriptionPart1 as String
   Public Overridable DescriptionPart2 as String

End Class

  • (1) 'IsLike' 方法被实现为 NHibernate Linq 扩展。从这里提取
于 2013-03-26T14:51:27.980 回答