From 6a0cc3758b9cb0bcff3f923472e2f099f96f774e Mon Sep 17 00:00:00 2001 From: Roman Rusakov Date: Thu, 6 Jul 2023 13:51:28 +0500 Subject: [PATCH 1/2] Red test for MultiMap when the split column is not present in the object and value is null --- tests/Dapper.Tests/MultiMapTests.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/tests/Dapper.Tests/MultiMapTests.cs b/tests/Dapper.Tests/MultiMapTests.cs index 097d95cd..9fe8fb37 100644 --- a/tests/Dapper.Tests/MultiMapTests.cs +++ b/tests/Dapper.Tests/MultiMapTests.cs @@ -268,7 +268,7 @@ public void TestMultiMapWithSplitWithNullValue() // https://stackoverflow.com/q/ } [Fact] - public void TestMultiMapWithSplitWithNullValueAndSpoofColumn() // https://stackoverflow.com/q/10744728/449906 + public void TestMultiMapWithSplitWithNotNullValueInSpoofColumn() // https://stackoverflow.com/q/10744728/449906 { const string sql = "select 1 as id, 'abc' as name, 1 as spoof, NULL as description, 'def' as name"; var product = connection.Query(sql, (prod, cat) => @@ -285,6 +285,21 @@ public void TestMultiMapWithSplitWithNullValueAndSpoofColumn() // https://stacko Assert.Null(product.Category.Description); } + [Fact] + public void TestMultiMapWithSplitWithNullValueInSpoofColumn() + { + const string sql = "select 1 as id, 'abc' as name, NULL as spoof, NULL as description, 'def' as name"; + var product = connection.Query(sql, (prod, cat) => + { + prod.Category = cat; + return prod; + }, splitOn: "spoof").First(); + // assertions + Assert.Equal(1, product.Id); + Assert.Equal("abc", product.Name); + Assert.Null(product.Category); + } + [Fact] public void TestMultiMappingVariations() { From 903f9982bd2e4672eb4d20ef7b22aaa7ccad6ad5 Mon Sep 17 00:00:00 2001 From: Roman Rusakov Date: Thu, 6 Jul 2023 14:06:57 +0500 Subject: [PATCH 2/2] Fix. When a field does not exist as a property of an object and its value is null, the object is not instantiated. --- Dapper/SqlMapper.cs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Dapper/SqlMapper.cs b/Dapper/SqlMapper.cs index daa62a3e..7cbb16b6 100644 --- a/Dapper/SqlMapper.cs +++ b/Dapper/SqlMapper.cs @@ -3547,6 +3547,26 @@ private static void GenerateDeserializerFromMap(Type type, DbDataReader reader, il.MarkLabel(finishLabel); } + else + { + if (first && returnNullIfFirstMissing) + { + Label finishLabel = il.DefineLabel(); + + il.Emit(OpCodes.Ldarg_0); // stack is now [target][reader] + EmitInt32(il, index); // stack is now [target][reader][index] + il.Emit(OpCodes.Callvirt, isDbNull); // stack is now [target][bool] + il.Emit(OpCodes.Brfalse_S, finishLabel); + + il.Emit(OpCodes.Pop); + il.Emit(OpCodes.Ldnull); // stack is now [null] + il.Emit(OpCodes.Stloc, returnValueLocal); + il.Emit(OpCodes.Br, allDone); + + il.MarkLabel(finishLabel); // stack is now [target] + } + } + first = false; index++; }