包含基本类型的Dapper映射结果

时间:2019-05-06 18:56:11

标签: c# dapper

我正尝试在数据库中查询一个较小的数据集(约80行),我需要在其中包含一个原始BIT来指示TestPartItem是否是TestPart的最后一项,使用以下查询:

SELECT tpt.[Name] TestPartTypeName,  1 AS split,
tpi.Number, tpi.Header, tpi.Instruction, tpi.Answer, tpi.[Description], 
tpi.Letter, 1 AS split,
tpo.Label, tpo.ImageFileName, 1 AS split,
CASE WHEN 
    (SELECT MAX(TestPartItemID) FROM TestPart_TestPartItem WHERE TestPartID = 1) = tpi.ID 
    THEN CAST(1 AS BIT)
    ELSE CAST(0 AS BIT) 
END AS IsLastItemInTestPart
FROM TestPart tp
JOIN TestPartType tpt ON tpt.ID = tp.TestPartTypeID
JOIN TestPart_TestPartItem tptpi ON tptpi.TestPartID = tp.ID
JOIN TestPartItem tpi ON tpi.ID = tptpi.TestPartItemID
JOIN TestPartItem_TestPartItemOption tpitpo ON tpitpo.TestPartItemID = tpi.ID
JOIN TestPartItemOption tpo ON tpo.ID = tpitpo.TestPartItemOptionID
WHERE tpi.ID = 1 AND tp.ID = 1

虽然我确实知道我也可以在TestPartItem表上添加位字段,但由于TestPart和{{ 1}}-给定的TestPartItem不一定是所有TestPartItem的最后一项

TestParts

不带var testPartItemDictionary = new Dictionary<int, TestPartItem>(); TestPartItemAggregate aggregate = new TestPartItemAggregate(); var result = conn.Query<TestPartType, TestPartItem, TestPartItemOption, bool, TestPartItem>(sql, (testPartType, testPartItem, testPartItemOption, IsLastItemInTestPart) => { TestPartItem tpi; if (!testPartItemDictionary.TryGetValue(testPartItem.ID, out tpi)) { tpi = testPartItem; aggregate.IsLastInTestPart = IsLastItemInTestPart; aggregate.TestPartTypeName = testPartType.Name; testPartItemDictionary.Add(testPartItem.ID, tpi); } tpi.TestPartItemOptions.Add(testPartItemOption); return tpi; }, splitOn: "split").Distinct().ToList(); aggregate.TestPartItem = testPartItemDictionary.Values.First(); bool的对象映射可以正常工作,但是在添加bool时,将引发异常,并显示以下消息:“ Invalid cast”

通过将强类型对象与基元结合起来,我只是向Dapper提出了太多要求吗? :-)

谢谢。

1 个答案:

答案 0 :(得分:0)

当选择1作为split时,split是一个int,而不是一点。如果您希望这样做,则必须返回CAST(1 AS BIT)AS split。 :)