3

I'm implementing my first Dapper.Net project. Now i'm wondering what's the easiest way to initialize an object that contains another object(multi mapping).

Here's my code:

public static IEnumerable<ShopPrefix> GetShopPrefixes(short fiSL) { using (var con = new SqlConnection(Properties.Settings.Default.RM2Con)) { const String sql = @" SELECT locShopPrefix.idShopPrefix, locShopPrefix.fiSL, locShopPrefix.fiShop, locShopPrefix.Prefix, locShopPrefix.Active, locShop.idShop, locShop.ShopName, locShop.ContactPerson, locShop.Street, locShop.ZIP, locShop.City, locShop.Telephone, locShop.Telefax, locShop.Email, locShop.ShopKey FROM locShopPrefix INNER JOIN locShop ON locShopPrefix.fiShop = locShop.idShop WHERE (locShopPrefix.fiSL = @fiSL);"; con.Open(); IEnumerable<Tuple<ShopPrefix,Shop>> shops = con.Query<ShopPrefix, Shop, Tuple<ShopPrefix, Shop>>( sql , (shopPrefix, shop) => Tuple.Create(shopPrefix, shop) , new { fiSL = fiSL }, splitOn: "idShop" ); foreach (var shop in shops) shop.Item1.Shop = shop.Item2; return shops.Select(t => t.Item1); } } 

So every shopPrefix belongs to (has) a Shop.

Q: Is this the correct way to map two objects since the Tuple approach with the following foreach to initialize the property Shop looks cumbersome?

1 Answer 1

4

I don't think you need a IEnumerable<Tuple<>> for a simple One-To-One object relationship. The following snippet should be sufficient as well.

var shopsPrefixes = con.Query<ShopPrefix, Shop, ShopPrefix>(sql , (shopPrefix, shop) => { shopPrefix.Shop = shop; return shopPrefix; } , new { fiSL = fiSL } , splitOn: "idShop" ); return shopsPrefixes; 
Sign up to request clarification or add additional context in comments.

4 Comments

+1 Thank you, that looks promising but now i'm getting "When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id". With the Tuple it worked. I'll modify your answer to show what i've changed (i need the ShopPrefixes instead of the Shops).
How does your DTO look exactly? If ShopPrefix is a child of Shop, I think you have to define the following as for the query types : Query<Shop, ShopPrefix, Shop>. I'm not sure if Dapper can do an inverse mapping from Child to Parent :)
Every ShopPrefix belongs to/has a Shop(FK in DB) whereas a Shop can have multiple prefixes. I want to initialize (possibly multiple) ShopPrefix with their related Shop.
You're right, only the order was wrong. So this works: con.Query<ShopPrefix, Shop, ShopPrefix>(the same order as in my original query). Thank you very much.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.