从一行中整理多个对象 [英] Dapper multiple objects from one row
本文介绍了从一行中整理多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一行来自数据库
select "John" Name,
"Male" Gender,
20 Age,
"Rex" PetName,
"Male" PetGender,
5 PetAge
// ... many more ...
使用Dapper,我想将此行拉入两个对象:
Using Dapper, I'd like to pull this row into two objects:
class Person
{
public string Name { get; set; }
public string Gender { get; set; }
public int Age { get; set; }
// ... many more ...
}
class Pet
{
public string PetName { get; set; }
public string PetGender { get; set; }
public int PetAge { get; set; }
// ... many more ...
}
注意:这里没有层次关系,我只是想将一个数据库行映射到两个(或更多)对象。
Note: there is no hierarchical relationship here, I'm simply trying to map one database row into two (or more) objects.
如何使用dapper做到这一点?
How can I do this using dapper?
- 我知道我可以通过返回动态值并手动映射每个对象来做到这一点,这很痛苦,因为在我的情况下,我们有很多列。我宁愿不这样做。 (而且,不能重新设计它以减少列数。)
我尝试过的操作:
- 我调查了
QueryMultiple< Person,Pet>
,但是它假设我正在运行多个查询。在我的现实生活中,这是一个非常昂贵的查询,我只想运行一次。 - 我还考虑过返回
Query< Person,Pet,Tuple< Person,Pet>>
,但这需要一个Id
列,此处没有层次结构关系或Id
s。我只想单行并将其映射到多列。
- I've looked into
QueryMultiple<Person,Pet>
, but it assumes I am running multiple queries. In my real-life scenario, this is a very expensive query, and I'd like to just run it once. - I've also looked into returning
Query<Person,Pet,Tuple<Person,Pet>>
, but this requires anId
column, here there's no hierearchical relationship orId
s. I just want to take a single row and map it to multiple columns.
推荐答案
使用 Query接近解决方案> code>方法。如果没有
Id
列,则可以提供 splitOn
参数:
You were pretty close to solution with the Query
method. If you don't have an Id
column, then you can provide a splitOn
argument:
connection.Query<Person, Pet, Tuple<Person, Pet>>(sql,
(person, pet) => Tuple.Create(person, pet), splitOn: "PetName");
这篇关于从一行中整理多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文