Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Properly handle value types when setting properties on dynamic objects returned by Dapper queries #2122

Merged
merged 1 commit into from
Oct 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}
}