Skip to content

Commit

Permalink
fix: properly handle value types when setting properties on dynamic o…
Browse files Browse the repository at this point in the history
…bjects returned by Dapper queries (#2122)
  • Loading branch information
alatanza authored Oct 13, 2024
1 parent b4f80b6 commit a3804ce
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
2 changes: 1 addition & 1 deletion Dapper/SqlMapper.DapperRowMetaObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public override System.Dynamic.DynamicMetaObject BindSetMember(System.Dynamic.Se
var parameters = new System.Linq.Expressions.Expression[]
{
System.Linq.Expressions.Expression.Constant(binder.Name),
value.Expression,
System.Linq.Expressions.Expression.Convert(value.Expression, typeof(object)),
};

var callMethod = CallMethod(setValueMethod, parameters);
Expand Down
42 changes: 39 additions & 3 deletions tests/Dapper.Tests/MiscTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1309,9 +1309,9 @@ public HazGetOnlyAndCtor(int idProperty, string nameProperty)
IdProperty = idProperty;
NameProperty = nameProperty;
}
}

[Fact]
}

[Fact]
public void Issue1164_OverflowExceptionForByte()
{
const string sql = "select cast(200 as smallint) as [value]"; // 200 more than sbyte.MaxValue but less than byte.MaxValue
Expand Down Expand Up @@ -1358,5 +1358,41 @@ public async Task QuerySplitStruct() // https://github.com/DapperLib/Dapper/issu

Assert.Single(results);
}

[Fact]
public void SetDynamicProperty_WithReferenceType_Succeeds()
{
var obj = connection.QueryFirst("select 1 as ExistingProperty");

obj.ExistingProperty = "foo";
Assert.Equal("foo", (string)obj.ExistingProperty);

obj.NewProperty = new Uri("http://example.net/");
Assert.Equal(new Uri("http://example.net/"), (Uri)obj.NewProperty);
}

[Fact]
public void SetDynamicProperty_WithBoxedValueType_Succeeds()
{
var obj = connection.QueryFirst("select 'foo' as ExistingProperty");

obj.ExistingProperty = (object)1;
Assert.Equal(1, (int)obj.ExistingProperty);

obj.NewProperty = (object)true;
Assert.True(obj.NewProperty);
}

[Fact]
public void SetDynamicProperty_WithValueType_Succeeds()
{
var obj = connection.QueryFirst("select 'foo' as ExistingProperty");

obj.ExistingProperty = 1;
Assert.Equal(1, (int)obj.ExistingProperty);

obj.NewProperty = true;
Assert.True(obj.NewProperty);
}
}
}

0 comments on commit a3804ce

Please sign in to comment.