Tinyint mapped with boolean fields in C#

c# dapper mysql

Question

I'm trying to map the 'tinyint' with 'boolean' field, but its giving me below issue. This issue is comming with local database only with live database its working fine. I don't understand where is issue, might be its region issue. I'm using dapper for mapping purpose. Please help me if you have any idea, below is copied exception.

A first chance exception of type 'System.Data.DataException' occurred in DAL.dll Additional information: Error parsing column 15 (IsBold=1 - SByte).

Expert Answer

Hmmm, that sounds like a bug. We handle many similar conversions.

The raw IL (using OpCodes.Conv_Ovf_I4) works fine in a local test; I'm slightly hampered here, because I don't have mysql locally, and all the servers I do have: only have unsigned tinyint. Is there any inner exception here, or something else I can work with? But: this is probably a question for the github issues list.


Expert Answer

I've installed MySql community edition (@@version reports 5.7.11-log). The following works fine on 1.50-beta9.

[FactMySql]
public void SO36303462_Tinyint_Bools()
{
    using (var conn = GetMySqlConnection(true, true, true))
    {
        try { conn.Execute("drop table SO36303462_Test"); } catch { }
        conn.Execute("create table SO36303462_Test (Id int not null, IsBold tinyint not null);");
        conn.Execute("insert SO36303462_Test (Id, IsBold) values (1,1);");
        conn.Execute("insert SO36303462_Test (Id, IsBold) values (2,0);");
        conn.Execute("insert SO36303462_Test (Id, IsBold) values (3,1);");

        var rows = conn.Query<SO36303462>("select * from SO36303462_Test").ToDictionary(x => x.Id);
        rows.Count.IsEqualTo(3);
        rows[1].IsBold.IsTrue();
        rows[2].IsBold.IsFalse();
        rows[3].IsBold.IsTrue();
    }
}
class SO36303462
{
    public int Id { get; set; }
    public bool IsBold { get; set; }
}

Please try 1.50-beta9. If that doesn't fix it, please help me to reproduce a failing test.


Popular Answer

You can make a quick extension to the datatype tinyint as so:

public static class IntExtensions
{
   public static bool AsBool(this int value)
  {
     return value != 0;
  }
}

Then you can use this anywhere in your code as such:

IsBold == 1.AsBool()


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why