dapper.net中的多映射

c# dapper

我正在實施我的第一個Dapper.Net項目。現在我想知道初始化包含另一個對象的對象(多映射)的最簡單方法是什麼。

這是我的代碼:

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);
    }
}

所以每個shopPrefix屬於(有) Shop

問:這是映射兩個對象的正確方法,因為Tuple方法使用以下foreach來初始化屬性Shop看起來很麻煩嗎?

一般承認的答案

我認為你不需要IEnumerable<Tuple<>>來獲得簡單的一對一對象關係。以下代碼段也應該足夠了。

var shopsPrefixes = con.Query<ShopPrefix, Shop, ShopPrefix>(sql
    , (shopPrefix, shop) =>
    {
        shopPrefix.Shop = shop;
        return shopPrefix;
    }
    , new { fiSL = fiSL }
    , splitOn: "idShop"
);
return shopsPrefixes;


許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因