问题
简单地说,映射没有按预期执行。局部变量reason
返回null,因此对nav
的赋值也将嵌套对象Reason
设置为null。
我在这里错过了一些简单的东西吗?
存储过程
ALTER PROCEDURE [PA].[spGetDocumentNavById]
-- Add the parameters for the stored procedure here
@DocumentNavID INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT
dn.DocumentNavID,
dn.IssuerName,
nt.Name,
dn.Amount,
dn.BTF,
dn.NavDate,
dn.ReceivedDate,
dn.PrimaryIdentifier,
dn.AssetID,
dh.LastModifiedBy,
dh.IsApproved,
dh.Corrected,
dh.ReasonID
FROM PA.DocumentNavs dn WITH(NOLOCK)
JOIN PA.NAVTypes nt WITH(NOLOCK)
ON nt.NAVTypeID = dn.NavTypeID
LEFT JOIN PA.DocumentsHistory dh WITH(NOLOCK)
ON dh.DocumentID = dn.DocumentID
LEFT JOIN PA.Analysts a WITH(NOLOCK)
ON a.AnalystID = dh.LastModifiedBy
WHERE dn.DocumentNavID = @DocumentNavID
C#
public DocumentNav FindById(int documentNavId)
{
var data = new
{
documentNavId
};
using (var conn = SqlConnection)
{
var response = conn.Query<DocumentNav, Reason, DocumentNav>("[PA].spGetDocumentNavById",
map: (nav, reason) =>
{
nav.Reason = reason;
return nav;
}, param: data, splitOn: "ReasonID", commandType: System.Data.CommandType.StoredProcedure)
.DefaultIfEmpty().FirstOrDefault();
return response;
}
}
答案 0 :(得分:0)
Dapper能够按Id列(“Id”或“id”)拆分返回的行查询。如果您的主键不同或者您希望将行拆分为Id以外的其他位置,请使用可选的“splitOn”参数。
在您的示例中,查询应如下所示:
SELECT
-- DocumentNav Object Columns
dn.DocumentNavID AS "Id",
dn.IssuerName,
-- ... all other DocumentNav properties..
-- Reason Object Columns
dh.ReasonID AS "Id"
dh.LastModifiedBy,
dh.IsApproved,
dh.Corrected
-- ... all other Reason properties..
FROM PA.DocumentNavs dn WITH(NOLOCK)
JOIN PA.NAVTypes nt WITH(NOLOCK)
ON nt.NAVTypeID = dn.NavTypeID
LEFT JOIN PA.DocumentsHistory dh WITH(NOLOCK)
ON dh.DocumentID = dn.DocumentID
LEFT JOIN PA.Analysts a WITH(NOLOCK)
ON a.AnalystID = dh.LastModifiedBy
WHERE dn.DocumentNavID = @DocumentNavID
您需要使用属性名称“Id”(DocumentNav&amp; Reason)