1

I know this general question is addressed in lots of areas but not for this specific scenario. I have the following objects

public class AuditRecord
{
    public long Id {get; private set; }
    public Collaborator IssuedBy { get; private set; }
}

public class Collaborator
{
    public Collaborator(Guid userId, string name, string email)
    {
        UserId = userId;
        Name = name;
        Email = email;
    }

    public Guid UserId { get; }

    public string Name { get; }

    public string Email { get; }
}

As you can see the IssuedBy property has a private setter. Is there a Dapper native way to handle this? The typical examples of passing a function that has the parts won't work because of the private accessor.

var resultData = await _connection.QueryAsync<AuditRecord, Collaborator, AuditRecord>(
    AUDIT_INSERT_SQL,
    (o, collaborator) =>
    {
        o.IssuedBy = collaborator;
        // Error CS0272 
        // The property or indexer 'AuditRecord.IssuedBy' cannot be used in this
        // context because the set accessor is inaccessible

        return o;
    }
);

Exposing the property as public or adding a method that does the same is essentially violating encapsulation rules.

David Liang
  • 20,385
  • 6
  • 44
  • 70
Steven
  • 860
  • 6
  • 24

1 Answers1

0

Currently Dapper only maps data automatically to matching private primitive types, like string, int, etc, but not complex types.

I posted a way to map data to private fields using reflections here. That should work well if you have any private field you need to map data to.

But in order to map data to private properties, I'm afraid you would have to use 2 sets of models, as what the accepted answer there proposed:

  • Your domain model that has all the encapsulations, private setters, etc
  • A set of models, usually called Persistence model, that reflects your database structure, and have all public getters and setters

That approach should work in your case:

  • First, you use Dapper to map data to your persistence models
  • Then you map your persistence models to your domain models. You can use tools like AutoMapper to help

I am using Dapper version 2.0.78, and still it doesn't support mapping data directly to private properties.

David Liang
  • 20,385
  • 6
  • 44
  • 70