dapper 可空bool转换出错及解决方案

最近使用entityframewok生成数据库,使用dapper来访问数据库,产生了一个意外的bug,下面是产生bug的示例以及解决方案。

由于用entityframework生成数据库,默认情况entityframewok 将bool?转换为tinyint(1),

使用dapper查询数据时报错(部分数据为空,部分数据不为空,且查询出来的第一条是可为空的数据才会出现问题,否则不会报错)。

1、定义一个类:

public class BugNullable
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public bool? IsBug { get; set; }

        public DateTime? UpdatedTime { get; set; }
    }

2、生成数据库表

CREATE TABLE `bugnullable` (
    `ID` INT(11) NOT NULL AUTO_INCREMENT,
    `Name` VARCHAR(50) NOT NULL DEFAULT '0',
    `IsBug` TINYINT(1) NULL DEFAULT NULL,
    `UpdatedTime` TIMESTAMP NULL DEFAULT NULL,
    PRIMARY KEY (`ID`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=3
;
3、填充数据

INSERT INTO `bugnullable` (`ID`, `Name`, `IsBug`, `UpdatedTime`) VALUES
    (1, 'test', NULL, NULL),
    (2, 'test1', 1, '2017-01-14 10:05:15');

4、dapper .net 测试代码

        class Program
    {
        static void Main(string[] args)
        {
            /// <summary>
            /// 数据库连接串
            /// </summary>
            var connectionString = ConfigurationManager.AppSettings["DefaultConnection"].Trim();
            using (var conn = new MySqlConnection(connectionString))
            {
                //var bugs = conn.Query<BugNullable>("select * from BugNullable order by ID asc;").ToList(); no bug
                SqlMapper.GridReader gr = conn.QueryMultiple("select * from BugNullable order by ID asc;");//bug
                var bugs = gr.Read<BugNullable>().ToList();

                bugs.ForEach(h => {
                    Console.WriteLine($"ID:{h.ID},Name:{h.Name},IsBug:{h.IsBug},UpdatedTime:{h.UpdatedTime}");
                });
                conn.Close();
            }
           
            Console.ReadLine();
        }
    }

    public class BugNullable
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public bool? IsBug { get; set; }

        public DateTime? UpdatedTime { get; set; }
    }

5、结果

6、解决方案:修改数据库字段大小(将bool对应的tinyint(1)适当扩大,如tinyint(2)或者bit(1))。

posted @ 2017-01-14 11:32  Mr.LUCKY  阅读(860)  评论(0编辑  收藏  举报