首页 > 解决方案 > 使用 Dapper 将多图子元素添加到父元素中

问题描述

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

数据模型非常基础:

在此处输入图像描述

当前结果返回一个重复的条目。 在此处输入图像描述

预期/期望

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

GROUP1 -> { USER_1, USER_2 }

组类

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; }
}

简洁的方法

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#databaseormdapper

解决方案


我的错,因为这里的代码显示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();

推荐阅读