【问题标题】:How to use external class when mapping objects in AutoMapper?在 AutoMapper 中映射对象时如何使用外部类?
【发布时间】:2018-01-06 15:58:16
【问题描述】:

我有一个实体对象,以及在我的应用程序的服务层中用作返回类型的 DTO 对象。我想使用 AutoMapper 将实体对象映射到 DTO 对象,反之亦然。我的一种类型,要执行映射,需要一些外部类来执行(即为某些字符串属性提供翻译)。在 AutoMapper 中是否有任何便捷的方法可以做到这一点?

【问题讨论】:

  • 是的,您可以使用依赖注入。文档是here

标签: automapper poco dto


【解决方案1】:

如果我理解你是正确的,这个例子就是你想要做的。 基于源属性,AutoMapper 将外部翻译映射到目标属性。

Dictionary<int, string> translations = new Dictionary<int, string>();
translations.Add(0, "Translation 0");
translations.Add(1, "Translation 1");
translations.Add(2, "Translation 2");

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<Class1, Class2>().ForMember(a => a.Translation, b => b.MapFrom(c => translations[c.Id]));
});

Class1 src = new Class1()
{
    Id = 1
};
Class2 dest = Mapper.Map<Class1, Class2>(src);

简单的类结构:

public class Class1
{
    public int Id { get; set; }
}

public class Class2
{
    public int Id { get; set; }
    public string Translation { get; set; }
}

【讨论】:

    猜你喜欢
    • 2021-04-30
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多