使用Guid Id的Dapper.net和Slapper.Automapper

4

我需要使用Dapper.net将一个一对多的扁平SQL查询映射到嵌套对象中。

Slapper.Automapper似乎是这样做的好方法;详见这个问题的答案:

如何在Dapper.Net中编写一对多查询?

使用Guids时出现错误的数据集: enter image description here

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 并不广泛使用,我在网上找不到关于这个问题的任何信息。)


谢谢。让我们退后一步 - 我只是在寻找一种填充对象集合的方法 - 并且这些对象在集合中本身又有一组对象。我只需要一种高效的方法来做到这一点。欢迎建议。我不想为了显示一个用户界面而连续20次访问数据库,这似乎是一个非常糟糕的想法。我想我可以在一次往返中获取结果集并手动填充对象,但这很麻烦,而且可能很慢。 - niico
在没有看到代码之前,我不确定你的使用情况,但我之前使用过 Dapper 和 Slapper 处理 GUID,并且没有遇到任何问题。 - Florian Haider
你能发布一下你正在测试的数据集吗? - Florian Haider
1
你的属性名称中包含大小写不同的字符,例如ContactIdg和ContactIDg。Slapper进行区分大小写的映射,请参见https://github.com/SlapperAutoMapper/Slapper.AutoMapper/issues/39。 - Florian Haider
哦 - 就这样了 - 如果您留下答案,我会接受的,谢谢。 - niico
显示剩余14条评论
1个回答

5

你的属性名中大小写不一,例如ContactIdgContactIDg。Slapper进行区分大小写的映射,请参见此问题


给你带来两个奖杯,以防你错过第一个。 - CelzioBR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接