【问题标题】:AutoMapper AfterMapAutoMapper AfterMap
【发布时间】:2015-02-02 22:33:44
【问题描述】:

我有一些类似于下面的代码,请参阅https://dotnetfiddle.net/wuE81t 的工作示例。

public class Program
{
    public static void Main()
    {
        Mapper.CreateMap<Foo, Bar>()
            .AfterMap((s, d) => {
                var stuff = SomeController.GetStuff(DateTime.Now.Second);
                d.Stuff = stuff.Contains(s.Name);
            });

        var foo = new List<Foo>() {
            new Foo() { Name = "joe", Age = 10 },
            new Foo() { Name = "jane", Age = 20 },
        };

        var bar = Mapper.Map<List<Foo>, List<Bar>>(foo);
    }
}

public class Foo
{
      public string Name { get; set; }
      public int Age { get; set; }
}

public class Bar
{
      public string Name { get; set; }
      public int Age { get; set; }
      public bool Stuff { get; set; }
}

public static class SomeController
{
    public static List<string> GetStuff(int currentUserId)
    {
        return new List<string>() { "jane" };
    }
}

我遇到的问题是对源列表中的每个项目都调用 GetStuff,这是一个相当繁重的操作,所以我想通过只调用一次来优化它。在我的实际代码中,GetStuff 使用 currentUserId 参数。

我目前已经通过将 GetStuff 移到 Mapper.Map 之后来解决它,但是由于我们有很多地方调用它,所以它比使用 AfterMap 难看得多。还有一个更大的风险是未来的开发人员会忘记所需的额外调用。

public static void Main()
{
    Mapper.CreateMap<Foo, Bar>();

    var foo = new List<Foo>() {
        new Foo() { Name = "joe", Age = 10 },
        new Foo() { Name = "jane", Age = 20 },
    };

    var bar = Mapper.Map<List<Foo>, List<Bar>>(foo);
    AddStuff(bar); // Required extra call!

    bar.Dump();
}

private static void AddStuff(List<Bar> bar)
{
    var stuff = SomeController.GetStuff(DateTime.Now.Second);
    foreach(var b in bar)
        b.Stuff = stuff.Contains(b.Name);       
}

有没有更好的解决方案?

【问题讨论】:

    标签: c# automapper


    【解决方案1】:

    问题在于 Automapper AfterMap 每次映射运行一次。您的映射配置是:

     Mapper.CreateMap<Foo, Bar>();
    

    因此,如果您将 AfterMap 扩展附加到此映射,它将在 Foo 和 Bar 之间的每个映射上运行它。这就是为什么你看到它运行了不止一次。

    如果您只想运行一次,则应将其附加到列表到列表的映射配置,而不是项目到项目的配置。但是 AutoMapper 不够灵活,无法轻松使用 List to List 配置。

    使其工作的一种方法是使用ConvertUsing 方法并明确指定要在列表项上使用的映射并在那里调用映射后的内容:

    Mapper.CreateMap<Foo, Bar>();
    
    Mapper.CreateMap<List<Foo>, List<Bar>>()
        .ConvertUsing(source =>
        {
            var mapped = source.Select(Mapper.Map<Foo, Bar>).ToList();
    
            // After mapping code;
            var stuff = SomeController.GetStuff(DateTime.Now.Second);
    
            return mapped;
        });
    

    【讨论】:

    • 在我将 AutoMapper 升级到 3.3.1 后,工作就像一个魅力,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 2020-10-21
    相关资源
    最近更新 更多