Skip to content

Commit a3804ce

Browse files
authored
fix: properly handle value types when setting properties on dynamic objects returned by Dapper queries (#2122)
1 parent b4f80b6 commit a3804ce

File tree

2 files changed

+40
-4
lines changed

2 files changed

+40
-4
lines changed

Dapper/SqlMapper.DapperRowMetaObject.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ public override System.Dynamic.DynamicMetaObject BindSetMember(System.Dynamic.Se
8181
var parameters = new System.Linq.Expressions.Expression[]
8282
{
8383
System.Linq.Expressions.Expression.Constant(binder.Name),
84-
value.Expression,
84+
System.Linq.Expressions.Expression.Convert(value.Expression, typeof(object)),
8585
};
8686

8787
var callMethod = CallMethod(setValueMethod, parameters);

tests/Dapper.Tests/MiscTests.cs

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1309,9 +1309,9 @@ public HazGetOnlyAndCtor(int idProperty, string nameProperty)
13091309
IdProperty = idProperty;
13101310
NameProperty = nameProperty;
13111311
}
1312-
}
1313-
1314-
[Fact]
1312+
}
1313+
1314+
[Fact]
13151315
public void Issue1164_OverflowExceptionForByte()
13161316
{
13171317
const string sql = "select cast(200 as smallint) as [value]"; // 200 more than sbyte.MaxValue but less than byte.MaxValue
@@ -1358,5 +1358,41 @@ public async Task QuerySplitStruct() // https://github.com/DapperLib/Dapper/issu
13581358

13591359
Assert.Single(results);
13601360
}
1361+
1362+
[Fact]
1363+
public void SetDynamicProperty_WithReferenceType_Succeeds()
1364+
{
1365+
var obj = connection.QueryFirst("select 1 as ExistingProperty");
1366+
1367+
obj.ExistingProperty = "foo";
1368+
Assert.Equal("foo", (string)obj.ExistingProperty);
1369+
1370+
obj.NewProperty = new Uri("http://example.net/");
1371+
Assert.Equal(new Uri("http://example.net/"), (Uri)obj.NewProperty);
1372+
}
1373+
1374+
[Fact]
1375+
public void SetDynamicProperty_WithBoxedValueType_Succeeds()
1376+
{
1377+
var obj = connection.QueryFirst("select 'foo' as ExistingProperty");
1378+
1379+
obj.ExistingProperty = (object)1;
1380+
Assert.Equal(1, (int)obj.ExistingProperty);
1381+
1382+
obj.NewProperty = (object)true;
1383+
Assert.True(obj.NewProperty);
1384+
}
1385+
1386+
[Fact]
1387+
public void SetDynamicProperty_WithValueType_Succeeds()
1388+
{
1389+
var obj = connection.QueryFirst("select 'foo' as ExistingProperty");
1390+
1391+
obj.ExistingProperty = 1;
1392+
Assert.Equal(1, (int)obj.ExistingProperty);
1393+
1394+
obj.NewProperty = true;
1395+
Assert.True(obj.NewProperty);
1396+
}
13611397
}
13621398
}

0 commit comments

Comments
 (0)