Pomelo.EntityFrameworkCore.MySql: Unable to cast object of type 'System.DBNull' to type 'System.String'
return (_context.Set<TEntity>().AsEnumerable())
I upgraded from dotnet 5 to 6 and now it started to get the error:
An exception occurred while iterating over the results of a query for context type 'KLog.Data.Context.KLogDbContext'.
System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.
at MySqlConnector.Core.Row.GetString(Int32 ordinal) in /_/src/MySqlConnector/Core/Row.cs:line 380
at MySqlConnector.MySqlDataReader.GetString(Int32 ordinal) in /_/src/MySqlConnector/MySqlDataReader.cs:line 283
at lambda_method2(Closure , QueryContext , DbDataReader , ResultContext , SingleQueryResultCoordinator )
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
Exception thrown: 'System.InvalidCastException' in Microsoft.EntityFrameworkCore.Relational.dll
Unhandled exception. System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.
at MySqlConnector.Core.Row.GetString(Int32 ordinal) in /_/src/MySqlConnector/Core/Row.cs:line 380
at MySqlConnector.MySqlDataReader.GetString(Int32 ordinal) in /_/src/MySqlConnector/MySqlDataReader.cs:line 283
at lambda_method2(Closure , QueryContext , DbDataReader , ResultContext , SingleQueryResultCoordinator )
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
at Program.<Main>$(String[] args) in /Users/homerokzam/Projects/KLog/webapi-develop/KLog.Migration/Program.cs:line 24
MySQL version: docker (latest) Operating system: MacOS with docker Pomelo.EntityFrameworkCore.MySql version: 6.0.0 Microsoft.AspNetCore.App version: net6.0
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 4
- Comments: 15 (4 by maintainers)
Do you have nullable reference types enabled in your csproj file? If so, you’ll need to change your model correspondingly.
I’ve opened https://github.com/mysql-net/MySqlConnector/issues/1135 to track this. Part of the acceptance criteria will be proving that it doesn’t regress performance.
nah, it’s not an issue. I set IsRequired() on a column that is nullable. So there would be that error when a null value was present.
For future readers. I used the following steps to come closer to a nullability model for our EF model. Turns out we had a few properties that were nullable, but should never be, so this actually fixed a few bugs with us 😃
*ModelSnapshot.csfile..IsRequired())*ModelSnapshot.csfile, and remove the migration files