我正在实施我的第一个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
看起来很麻烦吗?
答案 0 :(得分:3)
对于简单的一对一对象关系,我认为您不需要IEnumerable<Tuple<>>
。
以下代码段也应该足够了。
var shopsPrefixes = con.Query<ShopPrefix, Shop, ShopPrefix>(sql
, (shopPrefix, shop) =>
{
shopPrefix.Shop = shop;
return shopPrefix;
}
, new { fiSL = fiSL }
, splitOn: "idShop"
);
return shopsPrefixes;