Map multiple columns to single property with Dapper

c# dapper

Question

I'm working with a database that is mildly inconsistent in places. For example, there are two stored procedures that return basically the exact same result set structure, yet, for whatever reason, the DBA named the first field differently in one than the other. I don't want to create two separate models to encapsulate this data.

Is it possible for me to setup Dapper to map both of these result sets to the same object?

For example, sp_GetSomeDataByQtr returns a result set like:

Qtr int,
Lines int,
Balance money

While, sp_GetSomeDataByMonth returns a result set like:

Mo int,
Lines int,
Balance money

I want to encapsulate both of these into an object like

public class MyData {
    public int Term { get; set; } //This would be Qtr OR Mo depending on which SP is called.
    public int Lines { get; set; }
    public decimal Balance { get; set; }
}

So, then with Dapper:

MyData data = connection.Query<MyData>("sp_GetSomeDataByQtr", ...).FirstOrDefault();

or:

MyData data = connection.Query<MyData>("sp_GetSomeDataByMonth", ...).FirstOrDefault();

We can't change the Stored Procedures directly because there are legacy applications also retrieving data from them, and depending on these column names.

Is there a way to do this with Dapper? I know you can setup custom type maps, but I'm not sure how to do it when trying to map multiple columns names to a single property of an object.

Accepted Answer

What about something along the lines of below? Dapper will populate Mo or Lines depending on the stored procedure but you can always read the value from the Term property.

public class MyData
{
    public int? Mo { get; set; }
    public int? Lines { get; set; }
    public decimal Balance { get; set; }

    public int Term
    {
        get
        {
            if (Mo == null && Lines != null)
            {
                return Lines.Value;
            }
            if (Mo != null && Lines == null)
            {
                return Mo.Value;
            }

            return default(int);
        }
    }
}



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