Why am I receiving an EntitySqlException when executing a LINQ to Entities query that uses a custom DB Function?

痞子三分冷 提交于 2020-08-10 18:54:26

问题


As you may already know, when using LINQ to Entities with EF6 you can not use Int.TryParse or anything really trying to convert/cast a string to an int.

I've created a custom function convention below to mitigate this:

Public Class CustomFunctionConvention
    Implements IConceptualModelConvention(Of EdmModel)

    Public Sub Apply(item As EdmModel, model As DbModel) Implements IConceptualModelConvention(Of EdmModel).Apply

        Dim functionParseInt = New EdmFunctionPayload With {
        .CommandText = String.Format("TRY_PARSE(strValue AS INT)"),
        .Parameters = New List(Of FunctionParameter) From {
                {FunctionParameter.Create("strValue", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String), ParameterMode.In)}
            },
            .ReturnParameters = New List(Of FunctionParameter) From {
            {FunctionParameter.Create("ReturnValue", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32), ParameterMode.ReturnValue)}
            },
            .IsComposable = True
        }

        Dim parseFunction = EdmFunction.Create("ParseInt", model.ConceptualModel.EntityTypes.First().NamespaceName, DataSpace.CSpace, functionParseInt, Nothing)
        model.ConceptualModel.AddItem(parseFunction)
    End Sub
End Class

and the shared Function here

<DbFunction("Infrastructure.Data", "ParseInt")>
Public Shared Function ParseInt(value As String) As Integer
    Throw New NotImplementedException 'No implementation needed, defined in "Custom Conventions" region
End Function

I'm using this function in an orderby for a DB column that can contain either ints. e.g. 77,84,95, etc.. or string e.g. FHB,IWA,IDN or nulls

applicationsQuery = applicationsQuery _
    .OrderBy(Function(a) TheDbContext.ParseInt(a.DisplayRating))

When I go to execute the query

Dim appsWithData = Await theQuery.ToListAsync

It throws an EntitySqlException with message The query syntax is not valid. Near keyword 'AS'

I can not inspect the SQL generated because the exception is thrown before that happens, it is thrown during sql generation. Is there a way to view the SQL that caused the Exception?

My command text is quite simple so I'd imagine it is not a bug with EF6 but something I'm doing wrong. Am I doing something wrong?

来源:https://stackoverflow.com/questions/62923262/why-am-i-receiving-an-entitysqlexception-when-executing-a-linq-to-entities-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!