I want to map complex object to dapper result from query which has two inner joins. I know we\'ve solution to map one inner join but I want to map two inner joins result.
<
I decided to use Dapper to get a big data for calculating somethings. This is my dapper extension method to join 3 table in _RepositoryBase.cs file.
public List> QueryMultiple(string sql, object param)
where T2 : class
where T3 : class
{
using (var con = new SqlConnection(GetConnStr()))
{
if (con.State == ConnectionState.Closed)
con.Open();
var query = con.Query>(sql, (t, t2, t3, t4) => Tuple.Create(t, t2, t3, t4), param);
//if (query.Count() == 0)
// return new List();
var data = query.ToList();
con.Close();
con.Dispose();
return data;
}
}
Then, this function will help you to get sql joined data via dapper.
public List GetSqlJoinedDataViaDaper(int customerId)
{
var repo = new GenericRepository();
var sql = @"select table1.ID Table1ID, table1.*,
table2.ID Table2ID, table2.*,
table3.ID Table3ID, table3.*
from dbo.Table1 table1 (nolock)
left outer join dbo.Table2 table2 (nolock) on table2.ID=table1.FKTable2ID
left outer join dbo.Table3 table3 (nolock) on table3.ID=table1.FKTable3ID
where table1.CustomerID=@p1 ";
var resultWithJoin = repo.QueryMultiple(sql,
new { p1 = 1, splitOn = "Table1ID,Table2ID,Table3ID" }).ToList();
var retval = new List();
foreach (var item in resultWithJoin)
{
Table1 t1 = item.Item2; //After first split
t1.Table2 = item.Item3; //After Table2ID split
t1.Table3 = item.Item4; //After Table3ID split
retval.Add(t1);
}
return retval;
}
Summary: Write your select and insert split between tables. Say splits to Dapper and get your data. I used this and worked better than Entity Framework.