【发布时间】:2017-02-20 17:03:56
【问题描述】:
我需要使用 Dapper.net 将一对多的扁平化 SQL 查询映射到嵌套对象中。
Slapper.Automapper 似乎是这样做的好方法;如该问题的答案中所述:
How do I write one to many query in Dapper.Net?
public string MrFlibble3()
{
using (var connection = new SqlConnection(Constr))
{
Slapper.AutoMapper.Cache.ClearInstanceCache();
const string sql = @"SELECT tc.[IDG] as ContactIdg
,tc.[ContactName] as ContactName
,tp.[Idg] AS TestPhones_PhoneIdg
,tp.[ContactIdg] AS TestPhones_ContactIdg
,tp.[Number] AS TestPhones_Number
FROM TestContact tc
INNER JOIN TestPhone tp ON tc.Idg = tp.ContactIdg";
// Step 1: Use Dapper to return the flat result as a Dynamic.
dynamic test = connection.Query<dynamic>(sql);
// Step 2: Use Slapper.Automapper for mapping to the POCO Entities.
// - IMPORTANT: Let Slapper.Automapper know how to do the mapping;
// let it know the primary key for each POCO.
// - Must also use underscore notation ("_") to name parameters;
// see Slapper.Automapper docs.
Slapper.AutoMapper.Configuration.AddIdentifiers(typeof(TestContact), new List<string> { "ContactIDg" });
Slapper.AutoMapper.Configuration.AddIdentifiers(typeof(TestPhone), new List<string> { "PhoneIdg" });
var testContact = (Slapper.AutoMapper.MapDynamic<TestContact>(test) as IEnumerable<TestContact>).ToList();
string flibblethis = "";
foreach (var c in testContact)
{
foreach (var p in c.TestPhones)
{
// Console.Write("ContactName: {0}: Phone: {1}\n", c.ContactName, p.Number);
flibblethis += "Contact Name: " + c.ContactName + ". Number: " + p.Number + "<br />";
}
}
return flibblethis;
}
}
它在示例中运行良好 - 除了 Slapper.Automapper 如果 Id 是 Guid 而不是 ints 似乎不起作用。
是否有任何方法可以将 Guid ID 与 Slapper.Automapper 一起使用 - 或者是否有其他方法可以使用 Dapper.net 进行映射?
(Slapper.Automapper 没有被广泛使用,我在网上看不到任何关于这个问题的信息)。
【问题讨论】:
-
在查询中扁平化只是为了再水化成嵌套对象让我有点困惑。你为什么想做这个?如果值得将列放在一个结果集中,那么值得将它们放在一个 POCO 中,不是吗?
-
好的,我该怎么做?
-
我的想法是扁平化 = 1 个查询。我想在不为每个相关对象访问数据库的情况下执行此操作 - Slapper 在 ID 键控表方面做得很好。
-
我不相信。复杂性、处理、在线上更多数据的成本可能会超过仅使用 1 个查询的任何优势。我看到一些微型 ORM 这样做,Dapper 和 PetaPoco。我是这个领域的一个工具的作者,QueryFirst,(这可能对你有用。它处理 Guids)我想知道我是否应该加入这个功能。但后来我认为一个 sql 查询返回一个行集。你想要的 POCO 是一个封装了一行结果的 POCO。如果您不喜欢行集,请更改查询。保持简单。
-
您的属性名称中有不同的大写和小写,例如ContactIdg 和 ContactIDg。 Slapper 执行区分大小写的映射,请参阅github.com/SlapperAutoMapper/Slapper.AutoMapper/issues/39