2016-06-16 55 views
1

我正在爲Linq-to-sql構建表達式樹。在一些表格的數據庫中,相關列存儲爲string,而其中一些存儲爲Guid。我已經通過用Expression.Convert(Expression.Constant(search.PolicyNumber), policyNumberColumnLambda.Type)(其中PolicyNumber有時是nullable)包裝lambda常量來解決類似的問題,其中intint?工作得很好。但它不明顯地轉換爲Guidstring轉換。類型'System.Guid'和'System.String'之間沒有強制運算符定義

代碼看起來如下:

public static IQueryable<IRetrieveGuid> SearchByRetrieveGuid<IRetrieveGuid>(this IQueryable<IRetrieveGuid> queryable, SearchModel search) 
    { 
     var paramLambda = Expression.Parameter(typeof(IRetrieveGuid)); 
     var columnLambda = Expression.Property(paramLambda, "retrieveguid"); 
     var lambda = Expression.Lambda<Func<IRetrieveGuid, bool>>(
      Expression.Equal(columnLambda, Expression.Convert(Expression.Constant(search.RetrieveGuid), columnLambda.Type)), paramLambda); 
     return queryable.Where(lambda); 
    } 

如何轉換類型的表達式目錄樹相匹配?

+0

所以數據庫列是一個GUID?爲什麼不把它作爲一個quid並將其轉換爲linq-to-objects中的字符串? –

+0

@DStanley在某些表中它是GUID,而在某些字符串中。我正在通過接口來編寫一個面向方面的東西來查詢大規模混亂的數據庫(MSSQL和Oracle),並且我正在使用的接口是'Interface {T Property}',所以我不知道類型是事先(這可能解釋它: )http://stackoverflow.com/questions/37812584/putting-interface-behind-properties-with-same-name-but-different-types) –

回答

1

解決方法1:

這是一個數量級比溶液2快,但是如果你有多種可能性,可能會導致長期if elseswitch聲明

var retrieveGuidAsString = search.RetrieveGuid.ToString(); 
var constantLambda = columnLambda.Type.Name == "Guid" ? Expression.Constant(search.RetrieveGuid) : Expression.Constant(retrieveGuidAsString); 
var lambda = Expression.Lambda<Func<IRetrieveGuid, bool>>(Expression.Equal(columnLambda, constantLambda), paramLambda); 

溶液2:

This did work

public static IQueryable<IRetrieveGuid> SearchByRetrieveGuid<IRetrieveGuid>(this IQueryable<IRetrieveGuid> queryable, SearchModel search) 
    { 
     var paramLambda = Expression.Parameter(typeof (IRetrieveGuid)); 
     var columnLambda = Expression.Property(paramLambda, "retrieveguid"); 
     var lambda = Expression.Lambda<Func<IRetrieveGuid, bool>>(
      Expression.Equal(columnLambda, Expression.Call(Expression.Convert(Expression.Constant(search.RetrieveGuid), typeof (object)), typeof (object).GetMethod("ToString"))), paramLambda); 
     return queryable.Where(lambda); 
    } 

,但慢得令人難以置信,因爲它產生以下SQL

([Extent1].[retrieveguid] = 'c87d1234-46ad-47bf-9a9c-d9a35a454bd5' as uniqueidentifier) AS nvarchar(max))))) OR (([Extent1].[retrieveguid] IS NULL) AND (LOWER(CAST(cast('c87d1234-46ad-47bf-9a9c-d9a35a454bd5' as uniqueidentifier) AS nvarchar(max))) IS NULL)))

相關問題