Skip to content

Conversation

@ctrlpprint
Copy link

Re #2

I needed support for DefaultTypeMap.MatchNamesWithUnderscores in a project I was working on. I've created a minimal implementation and added passing unit tests. I don't believe it will break anything that was previously working,

There was a previous pull request for this in 2016 (DapperLib/Dapper#605) which was closed either because some of the AppendColumnNameEqualsValue methods may have been missed, or because there was a plan for something more general. In particular it looks like Column attributes were on the horizon (DapperLib/Dapper#722).

Essentially I've added a small method to wrap access to the property name:

    public static string ColumnName(string propertyName)
    {
        return DefaultTypeMap.MatchNamesWithUnderscores
            ? PascalCaseToSnakeCase(propertyName)
            : propertyName;
    }

and replaced references to column name with references to this method. Eg:

var sql = $"SELECT * FROM {name} WHERE {key.Name} = @id";
var val = res[property.Name];

become

var sql = $"SELECT * FROM {name} WHERE {ColumnMapping.ColumnName(key.Name)} = @id";
var val = res[ColumnMapping.ColumnName(property.Name)];

Were Column attributes to come into play, I'd imagine they would take precedence over direct access to the property name, so would equally take precdence over calls to ColumnMapping.ColumnName.

The Pascal to Snake Case method uses the following logic:

    public static string PascalCaseToSnakeCase(string pascalCaseString) {
        return string.Concat(pascalCaseString.Select((character, index)
             => index > 0 && char.IsUpper(character) ? "_" + character.ToString() : character.ToString())).ToLower();
    }

This will probably create unexpected results where acronyms are used in property names (eg the PersonID proprty would map to a person_i_d column), but I don't think there is any logical way around that.

Apologies if I've missed anything.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant