问题
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