简体   繁体   中英

Force MySQL Connector.NET to return a boolean value

If I have a table with a TINYINT(1) column and select this column with a DataReader MySQL creates a boolean column.

        var query = "SELECT column FROM table";
        using (var reader = ExecuteReader(query))
        {
            var schemaTable = reader.GetSchemaTable();
            var row = schemaTable.DefaultView[0];
            Assert.AreEqual(typeof(bool), row["DataType"]);
        }

However, If I have a query that does not work.

        var query = "SELECT false";
        using (var reader = ExecuteReader(query))
        {
            var schemaTable = reader.GetSchemaTable();
            var row = schemaTable.DefaultView[0];
            Assert.AreEqual(typeof(bool), row["DataType"]);
        }

This test fails because the DataType is System.Int64

Is it possible to force a query to return TINYINT(1) values? In the big picture I let Entity Framework generate my model and I have some views with boolean columns that are created as System.Int64 and I suppose this would solve the issue.

Have you tried using CONVERT or CAST?

 var query = "SELECT CONVERT(0,TINYINT(1))"
 var query = "SELECT CAST(0 AS TINYINT(1))"

Edit: this seems to be a limitation of the CAST/ CONVERT functions in MySQL. A suggested solution is to create a function to do the casting

 CREATE FUNCTION x_cast_to_tinyint(number bigint) RETURNS tinyint
 BEGIN    return number;
 END

Then call the function

select   x_cast_to_tinyint(d.tiny_int*1) as tiny

Reference: http://idiot-howto.blogspot.com/2008/07/mysql-cast-limitation.html#!/2008/07/mysql-cast-limitation.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM