2011-05-26 41 views
7

我有如下代码结构:写作小巧玲珑查询的嵌套对象

class Person 
{ 
    Name PersonName; 
    int Age; 
} 

class Name 
{ 
    string FirstName { get; set; } 
    string LastName { get; set; } 
} 

这里是我的存储过程,从数据库填充数据。

Create Procedure SpGetAllPersons 
As 
Select FirstName, LastName, Age from Persons 

如何编写将Dapper查询从数据库中提取所有人的Dapper查询?

例子:

List<Person> Persons = DbConn.Query<Person>("SpGetAllPersons", CommandType.StoredProcedure);

回答

8

你需要的,如果你要选择嵌套对象使用多映射。

这应该工作:

List<Person> persons = DbConn.Query<Name,Person,Person> 
    ("SpGetAllPersons", 
    (name,person) => {person.Name = name; return person;} 
    commandType: CommandType.StoredProcedure, 
    splitOn: "Age"); 

多映射器可以返回任何类型,甚至只是没有映射到任何数据库表的集合类型。

如果您打算分割任何不叫idId的东西,那么提供splitOn参数非常重要。

+0

这不适合我。我必须交换名称:'.Query (...,(person,name)=> ...')的位置。此外,splitOn:“年龄”也不适用于我 - 我不断收到此错误:“当使用多映射API时,确保您设置splitOn参数,如果您有其他键以外的键” – Trev 2011-07-16 00:04:34

+0

我误解了splitOn实际上是什么做...那部分工作正常...但我仍然需要交换'名称' – Trev 2011-07-16 02:09:01