Map from a Char to a Boolean

c# dapper

Question

We are using Dapper as an ORM to a legacy Informix database, and within this database boolean fields are actually stored as a Char, with 'F' meaning False and 'T' meaning True.

Within our POCO, we would like to expose a single boolean property and instruct Dapper to map to/from the relevant char value when reading from and writing to the database.

For Example:

Let's say we have a field within a table called "Active". The value in the database for the Active column will be either "T" of "F"

Our POCO may look something like this:

public class MyTable
{
    public bool Active { get; set; }
}

Is it possible to create a custom mapping within Dapper that for this column would set the Active property in the POCO to true if the underlying value is "T", and false if "F"?

One way I know I could work around this is to have two properties, one a string that Dapper can map to directly and another a boolean used by the consumers of the POCO. i.e:

public class MyTable
{
    public string Active { get; set; }
    public bool MyActive 
    {
        get { return Active == "T"; }
        set { Active = (value == "T"); }
    }
}

The disadvantage of this approach is having to maintain two properties so it would be a great if there is a way to extend dapper to get it to do this for me (particularly as there are a lot of fields like this within the table our database).

I've looked at implementing a custom type map but although this would work for a custom complex type, I'm not sure how it would work in this instance when I want to map from one basic type to a another basic type.

Accepted Answer

I doubt that dapper supports it, have a look at this related question's answer. As you can see the Active-property does not even have to be public, make it private to avoid confusion. However, i would name your bool property IsActive.

public class MyTable
{
    private string Active { get; set; }
    public bool IsActive 
    {
        get { return Active == "T"; }
        set { Active = value ? "T" : "F"; }
    }
}



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