How can I create 1 or 2 objects per row with dapper?

c# dapper sql-server

Question

I have a row with 4 columns of data. I want to create an object A from data in columns 1-2. If the data is not present in columns 1-2, use columns 3-4 to create an object B. In rare cases, we will have data in all columns, but data in columns 2 and 4 does not match. In that case, I want to return an object A and an object B.

Is there a way to do this in dapper using multi-mapping? Or should I return an object C that is all 4 columns, and then post process the data to create the objects A and B I actually want?

public class A {
  public long ID {get;set;}
  public long Value {get;set;}
}
public class B {
  public long ID {get;set;}
  public long Value {get;set;}
}

Objects A and B are not related to each other (i.e. A does not contain a list of B). So I am uncertain how to proceed.

Accepted Answer

If the data is partitioned by Id, then it should already work if you use a wrapper type to represent the two values. For example, if we use a Tuple<,>, then:

var data = conn.Query<A, B, Tuple<A, B>>(sql,(a, b) => Tuple.Create(a, b), args);


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