我需要使用Dapper.net将一个一对多的扁平SQL查询映射到嵌套对象中。
Slapper.Automapper似乎是这样做的好方法;详见这个问题的答案:
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;
}
}
这个例子中表现良好,但是如果 Id 是 GUID 而不是 int,则 Slapper.Automapper 似乎无法工作。
是否有办法使用 Slapper.Automapper 来映射 GUID ID,或者是否有其他使用 Dapper.net 的映射方法?
(Slapper.Automapper 并不广泛使用,我在网上找不到关于这个问题的任何信息。)