3

我正在实施我的第一个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看起来很麻烦?

4

1 回答 1

4

我认为您不需要一个IEnumerable<Tuple<>>简单的一对一对象关系。以下代码段也应该足够了。

var shopsPrefixes = con.Query<ShopPrefix, Shop, ShopPrefix>(sql
    , (shopPrefix, shop) =>
    {
        shopPrefix.Shop = shop;
        return shopPrefix;
    }
    , new { fiSL = fiSL }
    , splitOn: "idShop"
);
return shopsPrefixes;
于 2012-07-17T16:45:17.777 回答