140

I'm trying to use the multimapping feature of Dapper to return a list of ProductItems and associated Customers.

[Table("Product")]
public class ProductItem
{
    public decimal ProductID { get; set; }        
    public string ProductName { get; set; }
    public string AccountOpened { get; set; }
    public Customer Customer { get; set; }
} 

public class Customer
{
    public decimal CustomerId { get; set; }
    public string CustomerName { get; set; }
}

My Dapper code:

var sql = @"select * from Product p 
            inner join Customer c on p.CustomerId = c.CustomerId 
            order by p.ProductName";

var data = con.Query<ProductItem, Customer, ProductItem>(
    sql,
    (productItem, customer) => {
        productItem.Customer = customer;
        return productItem;
    },
    splitOn: "CustomerId,CustomerName"
);

This works fine, but I seem to have to add the complete column list to the "splitOn" parameter to return all the customers' properties. If I don't add "CustomerName", it returns null. Am I misunderstanding the core functionality of the multimapping feature? I don't want to have to add a complete list of column names each time.

Pang
  • 9,564
  • 146
  • 81
  • 122
Richard Forrest
  • 3,567
  • 2
  • 23
  • 32

7 Answers7

233

I just ran a test that works fine:

var sql = "select cast(1 as decimal) ProductId, 'a' ProductName, 'x' AccountOpened, cast(1 as decimal) CustomerId, 'name' CustomerName";

var item = connection.Query<ProductItem, Customer, ProductItem>(sql,
    (p, c) => { p.Customer = c; return p; }, splitOn: "CustomerId").First();

item.Customer.CustomerId.IsEqualTo(1);

The splitOn param needs to be specified as the split point, it defaults to Id. If there are multiple split points, you will need to add them in a comma delimited list.

Say your recordset looks like this:

ProductID | ProductName | AccountOpened | CustomerId | CustomerName 
---------------------------------------   -------------------------

Dapper needs to know how to split the columns in this order into 2 objects. A cursory look shows that the Customer starts at the column CustomerId, hence splitOn: CustomerId.

There is a big caveat here, if the column ordering in the underlying table is flipped for some reason:

ProductID | ProductName | AccountOpened | CustomerName | CustomerId  
---------------------------------------   -------------------------

splitOn: CustomerId will result in a null customer name.

If you specify CustomerId,CustomerName as split points, dapper assumes you are trying to split up the result set into 3 objects. First starts at the beginning, second starts at CustomerId, third at CustomerName.

Sam Saffron
  • 128,308
  • 78
  • 326
  • 506
  • 4
    Thanks Sam. Yeah your right it was the return order of the columns that was the issue with CustomerName | CustomerId being returned CustomerName was comming back null. – Richard Forrest Sep 20 '11 at 08:02
  • 44
    One thing to remember is you can't have spaces in the `spliton`, ie `CustomerId,CustomerName` not `CustomerId, CustomerName`, since Dapper doesn't `Trim` the results of the string split. It will just throw the generic spliton error. Drove me crazy one day. – jes Aug 29 '13 at 16:12
  • Dear Sam, I red that the default split-on is on `id` or `Id`. is it make difference if I have `ID` instead? – vaheeds Dec 13 '16 at 16:30
  • And, do I have to use `select a1,a2,b1,b2 from A join B` instead of `select * from A join B` to care about column order? – vaheeds Dec 13 '16 at 16:36
  • 4
    @vaheeds you should ALWAYS use column names and never use a star, it's gives sql less work to do, and you don't get situations where the column order is wrong, as in this case. – Harag May 26 '17 at 13:23
  • 6
    @vaheeds - regarding the id, Id, ID looking at the dapper code it's not case sensitive, and it also trims the text for the splitOn - this is v1.50.2.0 of dapper. – Harag May 26 '17 at 13:30
  • 1
    Might as well use nameof(Customet.CustomerID) to save some future pain. – BlackjacketMack Aug 05 '17 at 22:44
  • 5
    For anyone wondering, in case you have to split a query in 3 objects : on one column named "Id" and on one column named "somethingId", make sure to include the first "Id" in the split clause. Even though Dapper splits by default on "Id", in this case it has to be set explicitly. – Sbu Nov 09 '17 at 07:47
  • Does Dapper overlook the first column? Because it be odd if that was the case considering the splitOn value is id and it is standard for the first column to be id. – cubesnyc Jul 26 '20 at 19:40
  • This answer is really helpful to resolve null issue while getting MySQL data having one to many relationship using dapper! Spent few hours to resolve why certain properties do not bind and found that its the order of columns and from where to start spliton. – sanpat Mar 22 '22 at 23:37
36

Our tables are named similarly to yours, where something like "CustomerID" might be returned twice using a 'select *' operation. Therefore, Dapper is doing its job but just splitting too early (possibly), because the columns would be:

(select * might return):
ProductID,
ProductName,
CustomerID, --first CustomerID
AccountOpened,
CustomerID, --second CustomerID,
CustomerName.

This makes the splitOn: parameter not so useful, especially when you're not sure what order the columns are returned in. Of course you could manually specify columns... but it's 2017 and we just rarely do that anymore for basic object gets.

What we do, and it's worked great for thousands of queries for many many years, is simply use an alias for Id, and never specify splitOn (using Dapper's default 'Id').

select 
p.*,

c.CustomerID AS Id,
c.*

...voila! Dapper will only split on Id by default, and that Id occurs before all the Customer columns. Of course it will add an extra column to your return resultset, but that is extremely minimal overhead for the added utility of knowing exactly which columns belong to what object. And you can easily expand this. Need address and country information?

select
p.*,

c.CustomerID AS Id,
c.*,

address.AddressID AS Id,
address.*,

country.CountryID AS Id,
country.*

Best of all, you're clearly showing in a minimal amount of SQL which columns are associated with which object. Dapper does the rest.

Pang
  • 9,564
  • 146
  • 81
  • 122
BlackjacketMack
  • 5,472
  • 28
  • 32
  • This is a concise approach as long as no table has Id fields. – Bernard Vander Beken Jan 20 '20 at 11:09
  • With this approach a table can still have an Id field...but it should be the PK. You would just not have to create the alias so it's actually a little less work. (I would think it highly unusual (bad form?) to have a column called 'Id' that is not the PK.) – BlackjacketMack Jan 21 '20 at 13:44
  • You can also easily replace "Id" with any other column name, you would just need to have a splitOn parameter in that case. Since I inherited a DB where someone did indeed use Id as the name of a non-primary key column, I ended up using _ in place of Id. – Brandon Kramer Apr 11 '22 at 19:33
24

Assuming the following structure where '|' is the point of splitting and Ts are the entities to which the mapping should be applied.

       TFirst         TSecond         TThird           TFourth
------------------+-------------+-------------------+------------
col_1 col_2 col_3 | col_n col_m | col_A col_B col_C | col_9 col_8
------------------+-------------+-------------------+------------

Following is the Dapper query that you will have to write.

Query<TFirst, TSecond, TThird, TFourth, TResut> (
    sql : query,
    map: Func<TFirst, TSecond, TThird, TFourth, TResut> func,
    parma: optional,
    splitOn: "col_3, col_n, col_A, col_9")

So we want for TFirst to map to col_1 col_2 col_3, for TSecond to col_n col_m ...

The splitOn expression translates to:

Start mapping of all columns into TFirst till you find a column named or aliased as 'col_3', and also include 'col_3' into the mapping result.

Then start mapping into TSecond all columns starting from 'col_n' and continue mapping till new separator is found, which in this case is 'col_A', and mark the start of TThird mapping and so on.

The columns of the SQL query and the props of the mapping object are in a 1:1 relation (meaning that they should be named the same). If the column names resulting from the SQL query are different, you can alias them using the 'AS [Some_Alias_Name]' expression.

Pang
  • 9,564
  • 146
  • 81
  • 122
5

If you need to map a large entity write each field must be a hard task.

I tried @BlackjacketMack answer, but one of my tables has an Id Column other ones not (I know it's a DB design problem, but ...) then this insert an extra split on dapper, that's why

select
p.*,

c.CustomerID AS Id,
c.*,

address.AddressID AS Id,
address.*,

country.CountryID AS Id,
country.*

Doesn't work for me. Then I ended with a little change to this, just insert an split point with a name that doesn't match with any field on tables, In may case changed as Id by as _SplitPoint_, the final sql script looks like this:

select
p.*,

c.CustomerID AS _SplitPoint_,
c.*,

address.AddressID AS _SplitPoint_,
address.*,

country.CountryID AS _SplitPoint_,
country.*

Then in dapper add just one splitOn as this

cmd =
    "SELECT Materials.*, " +
    "   Product.ItemtId as _SplitPoint_," +
    "   Product.*, " +
    "   MeasureUnit.IntIdUM as _SplitPoint_, " +
    "   MeasureUnit.* " +
    "FROM   Materials INNER JOIN " +
    "   Product ON Materials.ItemtId = Product.ItemtId INNER JOIN " +
    "   MeasureUnit ON Materials.IntIdUM = MeasureUnit.IntIdUM " +
List < Materials> fTecnica3 = (await dpCx.QueryAsync<Materials>(
        cmd,
        new[] { typeof(Materials), typeof(Product), typeof(MeasureUnit) },
        (objects) =>
        {
            Materials mat = (Materials)objects[0];
            mat.Product = (Product)objects[1];
            mat.MeasureUnit = (MeasureUnit)objects[2];
            return mat;
        },
        splitOn: "_SplitPoint_"
    )).ToList();
Juan Pablo Gomez
  • 5,203
  • 11
  • 55
  • 101
4

There is one more caveat. If CustomerId field is null (typically in queries with left join) Dapper creates ProductItem with Customer = null. In the example above:

var sql = "select cast(1 as decimal) ProductId, 'a' ProductName, 'x' AccountOpened, cast(null as decimal) CustomerId, 'n' CustomerName";
var item = connection.Query<ProductItem, Customer, ProductItem>(sql, (p, c) => { p.Customer = c; return p; }, splitOn: "CustomerId").First();
Debug.Assert(item.Customer == null); 

And even one more caveat/trap. If you don't map the field specified in splitOn and that field contains null Dapper creates and fills the related object (Customer in this case). To demonstrate use this class with previous sql:

public class Customer
{
    //public decimal CustomerId { get; set; }
    public string CustomerName { get; set; }
}
...
Debug.Assert(item.Customer != null);
Debug.Assert(item.Customer.CustomerName == "n");  
3

I do this generically in my repo, works good for my use case. I thought I'd share. Maybe someone will extend this further.

Some drawbacks are:

  • This assumes your foreign key properties are the name of your child object + "Id", e.g. UnitId.
  • I have it only mapping 1 child object to the parent.

The code:

    public IEnumerable<TParent> GetParentChild<TParent, TChild>()
    {
        var sql = string.Format(@"select * from {0} p 
        inner join {1} c on p.{1}Id = c.Id", 
        typeof(TParent).Name, typeof(TChild).Name);

        Debug.WriteLine(sql);

        var data = _con.Query<TParent, TChild, TParent>(
            sql,
            (p, c) =>
            {
                p.GetType().GetProperty(typeof (TChild).Name).SetValue(p, c);
                return p;
            },
            splitOn: typeof(TChild).Name + "Id");

        return data;
    }
Ishmaeel
  • 14,138
  • 9
  • 71
  • 83
Dylan Hayes
  • 2,331
  • 1
  • 23
  • 33
0

I would like to note a very important aspect: the property name within the Entity must match the select statement. Another aspect of splitOn is how it looks for Id by default, so you don't have to specify it unless your naming is something like CustomerId, instead of Id. Let's look at these 2 approaches:

Approach 1

Entity Customer : Id Name

Your query should be something like:

SELECT c.Id as nameof{Customer.Id}, c.Foo As nameof{Customer.Name}.

Then your mapping understands the relationship between the Entity and the table.

Approach 2

Entity Customer: CustomerId, FancyName Select c.Id as nameof{Customer.CustomerId}, c.WeirdAssName As nameof{Customer.FancyName} and at the end of the mapping, you have to specify that the Id is the CustomerId by using the SplitOn.

I had an issue where I was not getting my values even though the mapping was correct technically because of a mismatch with the SQL statement.

Connor Low
  • 5,900
  • 3
  • 31
  • 52
alin
  • 39
  • 5