Last active
November 3, 2016 14:36
-
-
Save KerryRitter/459c88c68ef82519041e6a80421c09be to your computer and use it in GitHub Desktop.
Dapper relationship query example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using (var connection = new SqlConnection(_config["Connection"])) | |
{ | |
string query = @"SELECT * | |
FROM [Template] | |
WHERE [Type] = @type; | |
SELECT tct.TemplateId as TemplateId, tc.Name as CategoryName | |
FROM [TemplateCategory_Template] tct | |
JOIN [TemplateCategory] tc ON tct.TemplateCategoryId = tc.Id; | |
SELECT ts.TemplateId, ts.Url | |
FROM [TemplateScreenshots] ts | |
JOIN [Template] t on ts.TemplateId = t.Id | |
WHERE t.[Type] = @type;"; | |
using (var results = connection.QueryMultiple(query, new { type })) { | |
var templates = connection.Read<TemplateDto>(templatesQuery, new { type }).ToList(); | |
connection.Read<TemplateCategory>(templateCategoriesQuery) | |
.GroupBy(t => t.TemplateId).ToList() | |
.ForEach(categories => | |
{ | |
var template = templates.First(t => t.Id == categories.Key); | |
template.Categories = categories.Select(c => c.CategoryName).ToArray(); | |
}); | |
connection.Read<TemplateScreenshot>(templateScreenshotsQuery) | |
.GroupBy(t => t.TemplateId).ToList() | |
.ForEach(screenshots => | |
{ | |
var template = templates.First(t => t.Id == screenshots.Key); | |
template.Screenshots = screenshots.Select(c => c.Url).ToArray(); | |
}); | |
return templates; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment