【问题标题】:Adding multimap children into parent with Dapper使用 Dapper 将多图子元素添加到父元素中
【发布时间】:2019-02-12 11:57:38
【问题描述】:

我有一个非常简单的测试项目,我试图弄清楚如何将孩子添加到父母的集合中。

数据模型非常基础:

当前结果返回重复条目。

预期/期望

我希望结果是只有一个条目有两个孩子

GROUP1 -> { USER_1, USER_2 }

GROUP 类

public class GROUP
{
    public GROUP()
    {
        this.USERs = new HashSet<USER>();
    }

    public int Group_ID { get; set; }
    public string Name { get; set; }
    public string Location { get; set; }
    public ICollection<USER> USERs { get; set; }
}

用户类

public class USER
{
    public int User_ID { get; set; }
    public int Group_ID { get; set; }
    public string Name { get; set; }
    public Nullable<int> Age { get; set; }

    public GROUP GROUP { get; set; }
}

Dapper 方法

public GROUP Get(int id)
{
    string sqlGetGroupExtended = $"SELECT _group.Group_ID, _group.Name, _group.Location, _user.User_ID, _user.Name, _user.GROUP_ID, _user.Age FROM dbo.[GROUP] _group " +
                                        "LEFT JOIN dbo.[USER] _user ON _group.Group_ID = _user.Group_ID " +
                                        "WHERE _group.Group_ID = @groupid;";

    GROUP result = null;
    var lookup = new Dictionary<int, GROUP>();

    using (var connection = new SqlConnection(Properties.Settings.Default.CodeTest_DB))
    {
        var extendedGroup = connection.Query<GROUP, USER, GROUP>(sqlGetGroupExtended, (parent, child) =>
        {
            if (!lookup.TryGetValue(parent.Group_ID, out GROUP found))
            {
                lookup.Add(parent.Group_ID, found = parent);
            }
            found.USERs.Add(child);
            return found;
        }, param: new { groupid = id }, splitOn: "Location");

        // result = extendedGroup  <--- WHAT TO DO HERE?
    }

    return result;
}

我怎样才能做到这一点?

参考资料:

http://dapper-tutorial.net/dapper https://github.com/StackExchange/Dapper/blob/master/Dapper.Tests/MultiMapTests.cs#L12

【问题讨论】:

    标签: c# database orm dapper


    【解决方案1】:

    如果您使用的是 SQL Server 2016 或 Azure SQL,您可以提前使用 JSON 来返回分层对象:

    https://medium.com/dapper-net/one-to-many-mapping-with-dapper-55ae6a65cfd4

    这是我写的一篇关于这个主题的文章,连同源代码,展示了如何优雅地解决这个问题。

    【讨论】:

    • 很好,我喜欢这个选项。代码比“默认”更清晰
    【解决方案2】:

    我的错,代码在这里显示https://github.com/StackExchange/Dapper/blob/master/Dapper.Tests/MultiMapTests.cs#L12

    我错过了.Distinct()

    var extendedGroup = connection.Query<GROUP, USER, GROUP>(sqlGetGroupExtended, (parent, child) =>
    {
        if (!lookup.TryGetValue(parent.Group_ID, out GROUP found))
        {
            lookup.Add(parent.Group_ID, found = parent);
        }
        found.USERs.Add(child);
        return found;
    }, param: new { groupid = id }, splitOn: "Location,User_ID").Distinct();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 2017-10-22
      • 2019-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多