Search code examples
.netlinqsql-function

LINQ 'System.String' is not a valid return type for a mapped stored procedure method. SQL Function


I'am trying to use SQL user defined functions in LINQ. I've got the following function:

CREATE FUNCTION [TestSqlFunction] ( @strText VARCHAR(1000) )
RETURNS VARCHAR(1000)
AS 
    BEGIN
        RETURN @strText
    END
GO

This results in the following code:

<DateTimeVerification(DateTimeVerificationState.Verified)> _
<[Function](Name:="dbo.TestSqlFunction")> _
Friend Function TestSqlFunction_Linq(
<Parameter(Name:="strText", DbType:="varchar")>ByVal pstrText As String) As String
Dim result As IExecuteResult = Me.ExecuteMethodCall(Me, CType(MethodInfo.GetCurrentMethod, MethodInfo), 
pstrText)
Return CType(result.ReturnValue, String)
End Function

When executing this code it throws the following exception:

System.InvalidOperationException
'System.String' is not a valid return type for a mapped stored procedure method.
   at System.Data.Linq.SqlClient.QueryConverter.TranslateStoredProcedureCall(MethodCallExpression mce, MetaFunction function)
   at System.Data.Linq.SqlClient.QueryConverter.VisitMappedFunctionCall(MethodCallExpression mc)
   at System.Data.Linq.SqlClient.QueryConverter.VisitMethodCall(MethodCallExpression mc)
   at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
   at System.Data.Linq.SqlClient.QueryConverter.ConvertOuter(Expression node)
   at System.Data.Linq.SqlClient.SqlProvider.BuildQuery(Expression query, SqlNodeAnnotations annotations)
   at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
   at System.Data.Linq.DataContext.ExecuteMethodCall(Object instance, MethodInfo methodInfo, Object[] parameters)
   at DataContext.TestSqlFunction_Linq(String pstrText) 

It does work for functions with a integer as return value. The exception says "mapped stored procedure method", which I think is strange because it's a user defined function. Does anyone know how to fix this?


Solution

  • <DateTimeVerification(DateTimeVerificationState.Verified)> _
    <[FunctionAttribute](Name:="dbo.TestSqlFunction", IsComposable:=True)> _
    Friend Function TestSqlFunction_Linq(
    <Parameter(Name:="strText", DbType:="varchar")>ByVal pstrText As String) As String
    Dim result As IExecuteResult = Me.ExecuteMethodCall(Me, CType(MethodInfo.GetCurrentMethod,     MethodInfo), 
    pstrText)
    Return CType(result.ReturnValue, String)
    End Function
    

    To answer my onw question: Instead of using the <[function]> attribute you need to use the <[FunctionAttribute]> attribute. And also add the IsComposable:=True part makes all the difference.