Mapping multiple objects in dapper using Split-on

2019-08-31 13:26发布

问题:

Consider Role-Employee-Address

An employee can have only one role but can have many addresses. So using split on is not efficient as we may get the duplicates of roles and employee. We can use query multiple, but i feel if there is a way we can capture the role and employee together in one result and address in another, then that would be better.

In that case, instead of returning role and employee separately, we can directly join both in a single query and split on some column while mapping.

I'm expecting something like this

string query = "StoredProcedure";

using (var multi = connection.QueryMultiple(query, null))
{
    empRole = multi.Read<Employee,Role>().Single().SplitOn("Id");
    add = multi.Read<Address>().ToList();
}    

Is there any way we could do like this using both the techniques together?

回答1:

Correct, you need a One-To-Many mapping which is not natively supported by Dapper, but can be easily implemented if the database you're using supports JSON. Here's an article I wrote (along with working samples) that shows how you can do it using SQL Server / Azure SQL:

https://medium.com/dapper-net/one-to-many-mapping-with-dapper-55ae6a65cfd4



标签: dapper