dapper 可空bool轉換出錯及解決方案

來源:互聯網
上載者:User

標籤:avg   toe   gpl   bho   ++i   adl   zll   vmw   help   

最近使用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))。

dapper 可空bool轉換出錯及解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.