Skip to content

Issue handling properties with underscores and setters #1993

Closed
@jarrodls

Description

@jarrodls

I noticed an issue in 2.0.151 that I've traced down to the change in underscore handling 33090c0. This issue did not exist on 2.0.143.

There seems to be some issue with the logic that chooses what property to map to.

If you have a class like this, the setter on DisplayName never gets called and AltName never gets set.
This only seems to happen if the property has a backing field, if that backing field is above the other field (Display name in this case), and if the backing field has a { get; set; }.

private string _displayName { get; set; }
public string DisplayName {
    get => _displayName;
    set {
        _displayName = value;
        AltName = _displayName;
    }
}

public string AltName { get; set; }

If you move the backing field below DisplayName, the setter on DisplayName gets called as normal. It also works fine if you remove the { get; set; } from the backing field.
So this works fine with the backing field below.

public string DisplayName {
    get => _displayName;
    set {
        _displayName = value;
        AltName = _displayName;
    }
}

private string _displayName { get; set; }
public string AltName { get; set; }

The query I'm doing is just something like, using Npgsql.

return conn.QueryAsync<MyClass>("SELECT display_name FROM some_table;");

I also have DefaultTypeMap.MatchNamesWithUnderscores set to true.

Activity

mgravell

mgravell commented on Nov 11, 2023

@mgravell
Member

and if the backing field has a { get; set; }

then it isn't a backing field - it is another property; the code is already correctly preferring properties over fields (so: if you actually have a field _displayName, it works correctly), but this is an unexpected scenario. Let me see what we can do.

added a commit that references this issue on Nov 11, 2023

fix #1993 - when matching properties, prefer non-normalized property …

5472d04
mgravell

mgravell commented on Nov 11, 2023

@mgravell
Member

fixing, but honestly: I think you should just use a field here, not a property - i.e.

- private string _displayName { get; set; }
+ private string _displayName;
added a commit that references this issue on Feb 5, 2024

fix DapperLib#1993 - when matching properties, prefer non-normalized …

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @mgravell@jarrodls

        Issue actions

          Issue handling properties with underscores and setters · Issue #1993 · DapperLib/Dapper