Search code examples
c#sqlasp.net-mvcormdapper

Bool type return rule


I use dapper ORM.So i use two rules Query<T> & QuerySingle<T>. Query return the list & QuerySingle return the single object.

So,I want to get a bool type. (Actually I wanted to get a bool is true or false record).

My Query<T>:

public IEnumerable<T> Query<T>(string SqlString) where T : class
{
    return this.conn.Query<T>(SqlString);
}

So how can I write bool type return?


Solution

  • So, I want to get a bool type. (Actually I wanted to get a bool is true or false record)

    You can write a method like this:

    public bool GetBooleanValue(string sql)
    {
        return the_connection.Query<bool>(sql).FirstOrDefault();
    }
    

    The beauty about the FirstOrDefault is that when your query returns an empty row, Dapper will give you false. That suggested code will work as long as your query returns a value that can be translated into a boolean by your data provider. In case of SQL Server you would get:

    • TRUE for GetBooleanValue("select 1");
    • FALSE for GetBooleanValue("select 0");

    where 1 and 0 are values from a table column of boolean type.

    You can even use the code if you want to test if something exists or a group of values exists something like GetBooleanValue("select COUNT(*) from the_table where the_column='some_filter'").