diff --git a/Dapper.Tests/MiscTests.cs b/Dapper.Tests/MiscTests.cs index 857dcf9a2..2787f0149 100644 --- a/Dapper.Tests/MiscTests.cs +++ b/Dapper.Tests/MiscTests.cs @@ -1130,5 +1130,26 @@ private class HazGetOnly public int Id { get; } public string Name { get; } = "abc"; } + + [Fact] + public void GetOnlyPropertiesWithNonDefaultConstructor() + { + DefaultTypeMap.MatchNamesWithUnderscores = true; + var obj = connection.QuerySingle("select 42 as [id_property], 'def' as [name_property];"); + Assert.Equal(42, obj.IdProperty); + Assert.Equal("def", obj.NameProperty); + } + + private class HazGetOnlyAndCtor + { + public int IdProperty { get; } + public string NameProperty { get; } + + public HazGetOnlyAndCtor(int idProperty, string nameProperty) + { + IdProperty = idProperty; + NameProperty = nameProperty; + } + } } } diff --git a/Dapper/DefaultTypeMap.cs b/Dapper/DefaultTypeMap.cs index 8366ae5ee..bf1b23128 100644 --- a/Dapper/DefaultTypeMap.cs +++ b/Dapper/DefaultTypeMap.cs @@ -74,7 +74,8 @@ public ConstructorInfo FindConstructor(string[] names, Type[] types) int i = 0; for (; i < ctorParameters.Length; i++) { - if (!string.Equals(ctorParameters[i].Name, names[i], StringComparison.OrdinalIgnoreCase)) + if ((!MatchNamesWithUnderscores && !string.Equals(ctorParameters[i].Name, names[i], StringComparison.OrdinalIgnoreCase)) || + (MatchNamesWithUnderscores && !string.Equals(ctorParameters[i].Name, names[i].Replace("_", ""), StringComparison.OrdinalIgnoreCase))) break; if (types[i] == typeof(byte[]) && ctorParameters[i].ParameterType.FullName == SqlMapper.LinqBinary) continue; @@ -121,7 +122,17 @@ public SqlMapper.IMemberMap GetConstructorParameter(ConstructorInfo constructor, { var parameters = constructor.GetParameters(); - return new SimpleMemberMap(columnName, parameters.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.OrdinalIgnoreCase))); + var property = parameters.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.OrdinalIgnoreCase)); + + if (property == null && MatchNamesWithUnderscores) + { + property = parameters.FirstOrDefault(p => string.Equals(p.Name, columnName.Replace("_", ""), StringComparison.Ordinal)) + ?? parameters.FirstOrDefault(p => string.Equals(p.Name, columnName.Replace("_", ""), StringComparison.OrdinalIgnoreCase)); + } + + return new SimpleMemberMap( + MatchNamesWithUnderscores ? columnName.Replace("_", "") : columnName, + property); } ///