c# - 使用 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
解决方案
我的错,因为这里的代码显示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();
推荐阅读
- visual-studio - Visual Studio 2015/17 - Visual C++ 添加对项目的引用引用目标/输出库而不是项目
- java - 地图值在数组中。所有值都需要转换为列表并将所有值组合为结果列表
- libgdx - 如何优先处理事件处理 (LIBGDX)
- android - Xamarin.Forms - RelativeLayout 中的约束
- php - 无法登录 OpenCart,它显示无效令牌会话错误
- php - PHP PDO 保护数据库名称
- mysql - MySql 存储过程.... group_concat 中的错误
- c# - 无法使用 lambda 表达式设置带有 out 参数的函数
- django - 在 Django/Python 中,如何在正确验证后,在数据库中插入所需格式的字段数据?
- angular - 无法在 Angular 中显示从 firebase 检索的数据