class Person
{
Address Addr { get; set; }
int Age { get; set; }
}
class Address
{
string StreetName { get; set; }
County Cnty { get; set; }
}
class County
{
string CntyName;
string CntyCode;
}
这是我的存储过程,它填充数据库中的数据。
Create Procedure SpGetAllPersons
As
Select CntyName, CntyCode, StreetName, Age from Persons
我尝试在dapper查询下面编写但是获得异常
DBConn.Query<County, Address , Person, Person>
(DomainConstants.SpGetAllPersons,
(cnty, address, person) =>
{
address.Cnty = cnty;
person.Addr = address;
return person;
},
commandType: CommandType.StoredProcedure,
splitOn: "StreetName, Age").ToList();
我尝试使用以下概念,但它仅返回单个对象。我需要一份人员名单。
var sql =
@"select
1 as PersonId, 'bob' as Name,
2 as AddressId, 'abc street' as Name, 1 as PersonId,
3 as Id, 'fred' as Name
";
var personWithAddress = connection.Query<Person, Address, Extra, Tuple<Person, Address, Extra>>
(sql, (p, a, e) => Tuple.Create(p, a, e), splitOn: "AddressId,Id").First();
提前致谢。
答案 0 :(得分:11)
感谢马克和鲍勃跳过它。我能够以其他方式解决问题:
DBConn.Query(DomainConstants.SpGetAllPersons, commandType: CommandType.StoredProcedure)
.Select(x => new Person
{
Addr = new Address
{
Cnty = new County
{
CntyName = x.CntyName,
CntyCode = x.CntyCode
},
StreetName = x.StreetName
},
Age = x.Age
}).ToList();
答案 1 :(得分:-1)
嗯,在示例中,您只选择一行,因此 不会返回多行。但是,Query<T>
会返回IQueryable<T>
。您正在调用.First()
,因此您只得到一个结果就不足为奇了。如果您更改语句的最后部分以使用.ToList()
,您将获得每行包含一个项目的列表。