用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行也是集合,但没有书。
我在我的代码两个对象: MultiCollection 收集
都对应于在查询结果中给出的数据: 标识,用户标识和名称是对象MultiCollection。其他数据用于对象Collection。
我希望看到我的C#码连续3个MultiCollections: 行动 戏剧 小说
的行动将有2个集合。戏剧和小说应该是空的。
取而代之,我得到4个MultiCollections,并且它们都不包含Collections。我的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;
}, splitOn: "MultiCollectionId,CollectionId"););
}
}
通知书的,.Query<MultiCollection, Collection, MultiCollection>
是Collection
不List<Collection>
,它是做.add()
,而不是制定者。
现在我仍然得到4个MultiCollections,而不是3.前两个与每个相应的书相同。但是这两本书应该在一个多彩的选择下添加。 –
Ps。 a.Collections.add(s)应该是a.Collections.Add(s)(首都),并且a.Collections在第一次运行时为空,所以应该初始化......只是说,没有难过的感觉 –
@KenjiElzerman,yah, NP。我在没有任何IDE的情况下输入它。就在我头顶上。 – 12seconds
'a.Collections'是什么类型?它是一个列表? –
12seconds
是的,列表 –