I’m using Dapper to execute a stored procedure that joins multiple tables and maps the results to various related objects. The code works, but I find it a bit cumbersome and I’m not sure if I’m using the mapping correctly. Here’s the current implementation:
MainEntity? result = null;
await connection.QueryAsync(
sql: StoredProceduresConstants.GetDataById,
types: new[] { typeof(MainEntity), typeof(Setting), typeof(Catalog), typeof(Domain), typeof(User), typeof(User), typeof(EntityLanguage), typeof(Language) },
map: (objects) => { result ??= objects[0] as MainEntity ?? new();
if (objects[1] is not null) result.Settings.Add(objects[1] as Setting);
if (objects[2] is not null) result.Catalogs.Add(objects[2] as Catalog);
if (objects[3] is not null) result.Domains.Add(objects[3] as Domain);
result.CreatedBy = objects[4] as User;
result.ModifiedBy = objects[5] as User;
if (objects[7] is not null && objects[6] is not null)
{
var entityLanguage = objects[6] as EntityLanguage;
entityLanguage.Language = objects[7] as Language;
result.EntityLanguages.Add(entityLanguage);
}
return result;
},
splitOn: "Id",
param: parameters,
commandType: CommandType.StoredProcedure);
`
Any suggestions or examples would be greatly appreciated, is hard to find examples of this type of queries. Thanks!
I tried the code shown above and it’s working as supposed to but I’m not sure if I’m using the tool the right way.
GDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.