Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用Automapper映射到内部属性?_C#_Automapper 4 - Fatal编程技术网

C# 如何使用Automapper映射到内部属性?

C# 如何使用Automapper映射到内部属性?,c#,automapper-4,C#,Automapper 4,我们已经使用Automapper一段时间了,我们认为它非常实用,感谢您创建它 然而,我们有一个问题: 问题 “如何配置AutoMapper将源属性映射到内部目标属性?” 背景 在我们的分层体系结构中,Dto对象从不离开数据访问层,只允许域对象进出数据访问层。因此,从域POV来看,域对象不应该包含任何数据库知识。然而,在现实中,数据库ID是非常有用的,可以随身携带——期望“业务层”开发人员不知道它们 解决方案:将数据库ID添加到域对象中,但将其作为内部对象进行销售,这样它们就不会暴露在“业务层”中

我们已经使用Automapper一段时间了,我们认为它非常实用,感谢您创建它

然而,我们有一个问题:

问题

“如何配置AutoMapper将源属性映射到内部目标属性?”

背景

在我们的分层体系结构中,Dto对象从不离开数据访问层,只允许域对象进出数据访问层。因此,从域POV来看,域对象不应该包含任何数据库知识。然而,在现实中,数据库ID是非常有用的,可以随身携带——期望“业务层”开发人员不知道它们

解决方案:将数据库ID添加到域对象中,但将其作为内部对象进行销售,这样它们就不会暴露在“业务层”中。接下来,向数据访问层公开公共层(拥有域对象)内部。问题解决了。我们可能不知道如何让Automapper(>v3.3.0)使用我们的内部属性

在中,版本3.3.0
BindingFlags
被公开,用于解决问题

示例

公共.Dll

public class Person
{
   public Parent Father { get; set; }
   internal int FatherId {get; private set; }
}
DataAccess.dll

internal class PersonDto
{
   public ParentDto Father { get; set; }
   public int FatherId {get; private set; }
}
在Profile类中,我们有
CreateMap()

编辑1-修复了父亲返回类型中的错误

编辑2-添加更多信息

在Common.Dll中,我们有如下服务:

public class ParentService
{
    public Parent GetFather(Person person)
    {
        return repo.Parents.FirstOrDefault(parent => parent.Id = person.Father.Id);
    }
}
var father = parentService.GetFather(son);
// use father separately or assign it to the son. Like so:
// son.Father = father;
在Business.Dll中,开发人员使用的服务如下:

public class ParentService
{
    public Parent GetFather(Person person)
    {
        return repo.Parents.FirstOrDefault(parent => parent.Id = person.Father.Id);
    }
}
var father = parentService.GetFather(son);
// use father separately or assign it to the son. Like so:
// son.Father = father;
关键是,我们不希望业务开发人员能够从Businssess.Dll访问
son.FatherId
,也不希望他们能够访问创建域对象的Dto对象

因此,所有“数据库”知识都封装在各种Common.dll服务或DataAccess.dll中

谢谢。

这个问题已经回答了

为方便起见,我引用以下答案:

只需设置配置对象的ShouldMapProperty属性 在初始化方法中

下面是一个使用静态API的示例,但是,您应该能够 通过使用非静态API以类似的方式实现相同的功能

Mapper.Initialize(i=>
{
i、 ShouldMapProperty=p=>p.GetMethod.IsPublic | | p.GetMethod.IsAssembly;
i、 CreateMap();
});