【问题标题】:dapper how to map to private set property methodsdapper 如何映射到私有集属性方法
【发布时间】:2020-06-17 19:44:09
【问题描述】:

我知道这个一般性问题在很多领域都得到了解决,但不适用于这种特定情况。我有以下对象

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; }
}

如您所见,IssuedBy 属性有一个私有设置器。有没有一种 Dapper 原生的方式来处理这个问题?由于私有访问器,传递具有这些部分的函数的典型示例将不起作用。

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;
    }
);

将属性公开或添加执行相同操作的方法本质上违反了封装规则。

【问题讨论】:

    标签: c# dapper


    【解决方案1】:

    目前 Dapper 仅将数据自动映射到匹配的私有原始类型,如字符串、int 等,而不是复杂类型。

    我发布了一种使用反射here 将数据映射到私有字段的方法。如果您有任何需要将数据映射到的私有字段,这应该会很好。

    但是为了将数据映射到私有属性,恐怕您必须使用 2 组模型,正如那里接受的答案所建议的那样:

    • 具有所有封装、私有设置器等的域模型
    • 一组模型,通常称为 Persistence 模型,反映您的数据库结构,并具有所有公共 getter 和 setter

    这种方法应该适用于您的情况:

    • 首先,您使用 Dapper 将数据映射到您的持久性模型
    • 然后将持久性模型映射到域模型。您可以使用 AutoMapper 等工具来提供帮助

    我使用的是 Dapper 2.0.78 版,但它仍然不支持将数据直接映射到私有属性。

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      • 2021-12-11
      • 1970-01-01
      相关资源
      最近更新 更多