I have a simple max query:

sql.Append("Select Max(myID) from MyTable")

I then execute under my db context using entity framework

ctx.database.SqlQuery(Of Decimal)(Sql.ToString)

This runs fine if the select produces a value. However when the query returns nothing i get all sorts of casting issues. I have tried using "FirstOrDefault" and "DefaultIfEmpty" but still get errors like "The cast to value type 'System.Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."

I understand there is no value so the cast breaks, but I'm at a loss for a solution. Any help is appreciated.

有帮助吗?

解决方案

Looks like it's trying to stuff Null into a Decimal. Try to use a nullable decimal...

ctx.database.SqlQuery(Of Decimal?)(Sql.ToString)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top