天天看点

mysql和c#在类型转换的问题An unhandled exception occurred while processing the request.

1、char(36)和string

mysql在将char(36)类型的会转成System.GUID,如果char(36)字段里存的不是guid,最好不要用char(36),改成char(37)这样的就没事了。

在.net开放中(asp.net core\ef core\mysql)连接mysql数据库的时候,其中一个表字段类型是char(36),但里面存的并不是36位的,结果一直报如下错误

An unhandled exception occurred while processing the request.

FormatException: One of the identified items was in an invalid format.

MySqlConnector.Core.TextRow.GetValueCore(ReadOnlySpan<byte> data, ColumnDefinitionPayload columnDefinition) in 

C:\projects\mysqlconnector\src\MySqlConnector\Core\TextRow.cs

, line 57

后来看网络上回答才知道mysql将char(36)进行特殊处理了,具体mysql说明是这样的

https://dev.mysql.com/doc/connector-net/en/connector-net-8-0-connection-options.html

The back-end representation of a GUID type was changed from 

BINARY(16)

 to 

CHAR(36)

. This was done to allow developers to use the server function UUID()  to populate a GUID table - 

UUID()

 generates a 36-character string. Developers of older applications can add 

'Old Guids=true'

 to the connection string to use a GUID of data type BINARY(16).

2、tinyint(1)和boolean类型

System.InvalidCastException: Unable to cast object of type 'System.Boolean' to type 'System.SByte'.

如果在连接字符串中加入了TreatTinyAsBoolean=true,在mysql数据中的tinyint(1)类型转化到对应的.net中的sbyte类型时会报以上错误,所以改成TreatTinyAsBoolean=false就可以了。