Mapping one to many with Dapper(使用Dapper实现一对多映射)
本文介绍了使用Dapper实现一对多映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图弄清楚这一点,但我不能让它起作用。此查询:
select MultiCollections.*, Collections.* from MultiCollections
left join MultiCollectionCollections on MultiCollections.Id = MultiCollectionCollections.MultiCollectionId
left join Collections on MultiCollectionCollections.CollectionId = Collections.Id
where MultiCollections.UserId=5
这将返回以下数据:
如您所见,第1行和第2行来自同一个标题。它们背后的数据是书籍。 第3行和第4行也是集合,但没有书。
我的代码中有两个对象: 多集合 集合
两者都与查询结果中给出的数据相对应: ID、UserID和TITLE用于对象多集合。其他数据用于对象集合。 我希望在我的C#代码中看到三个多集合: 动作 话剧 小说操作将有2个集合。戏剧和虚构应该为空。
相反,我得到了4个多集合,其中没有一个包含集合。我的C#代码:
public IEnumerable<MultiCollection> GetAll(int userId)
{
string query = @"select MC.*, C.* from MultiCollections MC
left join MultiCollectionCollections MCC on MC.Id = MCC.MultiCollectionId
left join Collections C on MCC.CollectionId = C.Id
where UserId=" + userId;
using (DbConnection connection = ConnectionFactory())
{
connection.Open();
return connection.Query<MultiCollection, List<Collection>, MultiCollection>(query,
(a, s) =>
{
a.Collections = s;
return a;
});
}
}
运行代码时,我预期如下:
Action
Collections
-> Book 1
-> Book 2
Drama
Collections
Null
Fiction
Collections
Null
我不知道我做错了什么。
推荐答案
您的C#代码应该如下所示:
public IEnumerable<MultiCollection> GetAll(int userId)
{
string query = @"select MC.*, C.* from MultiCollections MC
left join MultiCollectionCollections MCC on MC.Id = MCC.MultiCollectionId
left join Collections C on MCC.CollectionId = C.Id
where UserId = @userId;";
using (DbConnection connection = ConnectionFactory())
{
connection.Open();
return connection.Query<MultiCollection, Collection, MultiCollection>(query,
(a, s) =>
{
a.Collections = new List<Collection>();
a.Collections.Add(s);
return a;
},
param: new { userId },
splitOn: "MultiCollectionId,CollectionId");
}
}
请注意,.Query<MultiCollection, Collection, MultiCollection>
是Collection
而不是List<Collection>
,它正在执行.add()
而不是setter。
这篇关于使用Dapper实现一对多映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:使用Dapper实现一对多映射


基础教程推荐
猜你喜欢
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01