Created
August 20, 2020 22:08
-
-
Save kaanacar34/0272b266bd71882307da39be5739dcee to your computer and use it in GitHub Desktop.
DAPPER MULTIPLE MAPPING THREE LEVELS
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
public class Category | |
{ | |
public int CategoryId { get; set; } | |
public string CategoryName { get; set; } | |
public ICollection<Product> Products { get; set; } | |
} | |
public class Product | |
{ | |
public int ProductId { get; set; } | |
public string ProductName { get; set; } | |
public int CategoryId { get; set; } | |
public Category Category { get; set; } | |
public int ProductOriginId { get; set; } | |
public ProductOrigin ProductOrigin { get; set; } | |
} | |
public class ProductOrigin | |
{ | |
public int ProductOriginId { get; set; } | |
public string ProductOriginName { get; set; } | |
} | |
public static async Task<List<Category>> GetCategoryWithProducts() | |
{ | |
using (var connection = new SqlConnection(connString)) | |
{ | |
var sql = @" SELECT c.CategoryId,c.CategoryName,p.ProductId,p.ProductName,po.ProductOriginName | |
FROM Categories c | |
LEFT JOIN Products p ON p.CategoryId=c.CategoryId | |
LEFT JOIN ProductOrigins po on po.ProductOriginId=p.ProductOriginId"; | |
var categoryDictionary = new Dictionary<int, Category>(); | |
var list = connection.QueryAsync<Category, Product, Category>( | |
sql, | |
(category, product) => | |
{ | |
Category categoryentry; | |
if (!categoryDictionary.TryGetValue(category.CategoryId, out categoryentry)) | |
{ | |
categoryentry = category; | |
categoryentry.Products = new List<Product>(); | |
categoryDictionary.Add(categoryentry.CategoryId, categoryentry); | |
} | |
categoryentry.Products.Add(product); | |
return categoryentry; | |
}, | |
splitOn: "CategoryId,ProductId").Result | |
.Distinct() | |
.ToList(); | |
// Console.WriteLine(list.Count); | |
return list.ToList(); | |
} | |
} | |
with the code category> product, I can buy the category and the products under the category together. | |
I want to get a list like category> product> productorigin. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment