我知道在许多领域都解决了这个一般性问题,但不是针对这个特定的场景。我有以下对象
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
属性有一个私有setter。有没有一种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;
}
);
将属性公开为公共属性或添加执行相同操作的方法实质上违反了封装规则。
目前,dapper仅自动将数据映射到匹配的私有基元类型,如字符串、int等,而不是复杂类型。
我发布了一种使用反射将数据映射到私有字段的方法here。如果您有任何需要将数据映射到的私有字段,这应该可以很好地工作。
但为了将数据映射到私有属性,恐怕您必须使用两套模型,正如那里公认的答案所建议的那样:
包含所有封装、私有setter等的域模型 一组模型,通常称为持久性模型,它反映了您的数据库结构,并具有所有公共的getter和setter该方法应该适用于您的情况:
首先,使用Dapper将数据映射到持久性模型 然后将持久性模型映射到域模型。您可以使用AutoMapper之类的工具来帮助我使用的是Dapper版本2.0.78,但它仍然不支持将数据直接映射到私有属性。