ExecuteQuery 对 bit/bool 类型的处理

ExecuteQuery 对 bit/bool 类型的处理

SQL Server 中 bit 类型存储为 0/1,但 ExecuteQuery<T> 映射到 C# bool 时可能出现转换问题。解决办法是借助一个中间属性间接判断。

class Program
{
    static void Main(string[] args)
    {
        using (var dbContext = new DataClasses1DataContext())
        {
            var total = dbContext.ExecuteQuery<int>("select count(1) from [user]").FirstOrDefault();//4
            var list = dbContext.ExecuteQuery<UserEx>("select * ,1 as Enable from [user]").ToList();
        }
    }
}

class UserEx
{
    public long ID { set; get; }
    public string Name { set; get; }
    public string Password { set; get; }
    public int? Status { set; get; }
    public DateTime AddTime { set; get; }
    public int Enable { set; get; }
    public bool IsEnable { get { return Enable == 1; } set { } }//借助额外属性判断
}Code language: JavaScript (javascript)

说明:

问题原因解决方式
ExecuteQuery<User> 映射 bool 失败SQL Server bit 返回 True/FalseExecuteQuery 无法直接转 C# boolint 接收,再加一个 bool 计算属性
SQL 中 select * ,1 as Enable新增一列 Enable 映射为 int实体类中 Enable 接收该列值
IsEnable 属性只读计算属性,get 中判断 Enable == 1对外暴露 bool,内部用 int 中转

SQL Server bit 与 C# bool 对应关系:

SQL Server bitC#
1 / Truetrue
0 / Falsefalse
NULLnull(需 bool?

关键要点:

要点说明
ExecuteQuery 映射列名匹配属性名,类型需兼容
bit → bool 失败int 中间字段接收
计算属性bool 属性 get 中判断 int
SQL 中加列select *, 1 as Enable 为每行加固定值列
替代方案ExecuteQuerybit 列时改为 cast(col as int)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注