开发者

Automapper (C#): Nested mappings not working

I have a simple mapping and it is working but it's not filling in Output.Details.

I am a bit confused, I think it maybe because I am using the source as "Task" for each one.

  Mappe开发者_如何学JAVAr.CreateMap<Task, Output>();


  Mapper.CreateMap<Task, Output.Details>().ForMember(
       dest => dest.Item, opt => opt.MapFrom(src => src.Name));

As far as i know i have to create 2 maps, 1 for the object and 1 for object contained within.

Problem is the source for the OUTPUT and OUTPUT.DETAILS can be found in TASK

I tried delving into Details within the first map and specifying Mapfrom but it gives the following error which is why i must create 2 maps

         must resolve to top-level member. Parameter name: lambdaExpression error

  IList<Task> tempItems= GetItems();

        IList<Output> items =
            Mapper.Map<IList<Task>, IList<Output>>(tempItems);

The map works but my property "Item" availble in Output.Details is NULL

What am I doing wrong? Here is my Destination object.

It fills in Name no problem, but nothing inside DETAILS... they are left NULL.

Task is not my class, but I checked it and all values are there to be copied hence Tag has a value and is a STRING.

public class Output   
{
    public string Name { get; set; }

    public Details Summary { get; private set; }
 
    public class Details
    {
        public string Item{ get; set; }
    }

    public Output()
    {
        Summary = new Details();
    }
}

EDIT

Here is an example of the Task class.

Automapper (C#): Nested mappings not working

EDIT

They is a sample vs 2010 project here and it shows exactly the problem.

http://dl.dropbox.com/u/20103903/AutomapperNotWorking.zip

and here is an image showing the issue, as you can see Summary Item is "NULL" but it should contain the NAME from Task.

Automapper (C#): Nested mappings not working


First off, always use Mapper.AssertConfigurationIsValid(); to make sure your mapping configuration is valid. I added it to your code and it immediately highlighted the problem: You didn't tell Automapper what to do with the Summary property. Since Task doesn't contain a property called Summary, Automapper needs to know what to do with it.

So the problem isn't really how to map a nested class, you just need to tell Automapper what to do with Summary. Here's the Automapper configuration that works for your example:

Mapper.CreateMap<Task, Output>()
    .ForMember(d => d.Summary, o => o.MapFrom(t => new Output.Details {Item = t.Name}));
Mapper.AssertConfigurationIsValid();

That's all you need.


for the new version, it can be performed as follow:

var config = new MapperConfiguration(cfg => {
    cfg.CreateMap<UdtDevQuestion, QuestionViewModel>();
});
config.AssertConfigurationIsValid();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜