Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
708 views
in Technique[技术] by (71.8m points)

c# - Automapper: mapping collection and passing parameter

I am trying to map one entity to another (which has one additional field).

Group {
    int Id;
}

GroupExtended {
   int Id;
   string Description;
}

So I do the mapping in loop:

foreach (var group in groups)
{
     var result = mapper.Map<Group, GroupExtended>(group,
                        opt => opt.AfterMap((src, dest) => dest.Description = someValue));
}

Is that possible to map entire IEnumerable, and still passing an the value ? I tried this:

var result = mapper.Map<List<GroupExtended>>(groups,
                        opt => opt.AfterMap((src, dest) => dest.Description = someValue));

But it has an error on dest.Description : 'object' does not contain definition of "Description"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, it is possible to map an entire collection and still pass the value. Using a custom value resolver is probably the preferred option, as pointed out in the comment on your original post. If you'd still prefer to use AfterMap, you can do something like the following, remembering that your source and destination in this case are collections rather than individual items:

var result = mapper.Map<List<Group>, List<GroupExtended>>(groups,
    opt => opt.AfterMap((src, dest) =>
    {
        foreach (var i in dest)
        {
            i.Description = "someValue";
        }
    }));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...