2012-06-11 33 views
1

我正在使用遺留數據,這往往會使我在多列中分割出一個信息。我試圖重現以下SQL查詢...NHibernate QueryOver:從範圍''引用的'SomeTable'類型的變量'line',但沒有定義

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,連接表達式+像函數一樣起着魅力的作用)。

回答

0

爲了記錄在案,我使用Linq解決了這個問題。

我的問題(我的錯,我沒有提到過)的主要觀點是重用基類代碼的可能性,所以我想提取給定表的描述表達式以將其用於多種用途。最終的想法是如下實現的:

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

有點冗長,但它的工作原理

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(); 
相關問題