【发布时间】: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