为嵌套对象编写Dapper查询

9

我有如下的代码结构:

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查询以从数据库中获取所有人的信息?
例如: List<Person> Persons = DbConn.Query<Person>("SpGetAllPersons", CommandType.StoredProcedure);
1个回答

8

如果您想选择嵌套对象,需要使用多重映射器。

以下代码应该可行:

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

多重映射器可以返回任何类型,甚至只是一个未映射到任何数据库表的聚合类型。
如果您打算拆分任何不叫做idId的东西,则提供splitOn参数非常重要。

这对我没用。我不得不交换Name的位置:.Query<Person, Name, Person>(..., (person, name) => ... )。另外,splitOn: "Age" 对我也不起作用 - 我一直收到这个错误:“当使用多映射API时,请确保设置splitOn参数,如果您有除Id之外的键”。 - Trev
我误解了splitOn实际上在做什么...那部分工作正常...但我仍然需要交换“Name”。 - Trev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接