天天看點

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就可以了。