我的存储过程返回用户列表以及关系表中的组织详细信息。
我已经使用dapper在我的C#Web API应用程序中执行存储过程。
我是新手,精打细算。如何将存储过程返回的结果映射到我的模型?
CREATE PROCEDURE [dbo].[GetAllUsersByOrganisation]
@OrganisationId int = 0
AS
SELECT * from dbo.Users u
inner join dbo.Organisations org on u.OrganisationId = org.Id
Where u.OrganisationId = @OrganisationId
public List<User> GetUseryOrganisation(int organisationId)
{
var users = DataContextFactory.GetConnectionString(_settings)
.Execute("dbo.GetAllUsersByOrganisation", new {OrgantisationId = organisationId},
commandType: CommandType.StoredProcedure);
// Map to return List of User
}
public class User
{
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
public string EmailAddress { get; set; }
public Organisation Organisation { get; set; }
}
public class Organisation
{
public int Id { get; set; }
public string Name { get; set; }
}
答案 0 :(得分:3)
您应该使用Query
重载,它需要返回记录集中的两种类型(用户数据和组织数据),然后将组织数据分配给用户实体:
var users = DataContextFactory.GetConnectionString(_settings)
.Query<User, Organisation, User>(
"dbo.GetAllUsersByOrganisation",
(u,o) => { u.Organisation = o; return u; }, // map function
new {OrgantisationId = organisationId},
commandType: CommandType.StoredProcedure);
return users.ToList();