7

Why does automapper create empty instances of collections if they are null? Here is my configuration

public class MapperProfile : Profile
{
    protected override void Configure()
    {
        AllowNullCollections = true;
        AllowNullDestinationValues = true;
        Mapper.CreateMap<User, DAL.Models.User>();
        Mapper.CreateMap<DAL.Models.User, User>();
        Mapper.CreateMap<Role, DAL.Models.Role>();
        Mapper.CreateMap<DAL.Models.Role, Role>();
        Mapper.CreateMap<Task, DAL.Models.Task>();
        Mapper.CreateMap<DAL.Models.Task, Task>();
        Mapper.CreateMap<TaskReport, DAL.Models.TaskReport>();
        Mapper.CreateMap<DAL.Models.TaskReport, TaskReport>();
        Mapper.CreateMap<Project, DAL.Models.Project>();
        Mapper.CreateMap<DAL.Models.Project, Project>();
    }
}

My models have the same properties:

public class User
{
    public virtual List<Task> Tasks { get; set; }

    public virtual List<Role> Roles { get; set; }

    public virtual List<TaskReport> TaskReports { get; set; } 
}

In my MVC project in Global.asax I'm just add my profile like this:

Mapper.AddProfile(new BL.MapperProfile());

Thanks!

3
  • 1
    How are you creating the mapping in the code? Commented Nov 22, 2015 at 18:19
  • I've modified my question. Hope it clarify it a bit Commented Nov 22, 2015 at 19:29
  • I was able to re-create the issue after your edits and have updated my answer. Commented Nov 22, 2015 at 22:12

1 Answer 1

13

Sorry, my first answer was off the mark. I was able to re-create the issue and find out what's going on.

You are getting this error because of the static call to Mapper.CreateMap method. If you change your code to just call the non static CreateMap method you should be good.

public class MapperProfile : Profile
{
    protected override void Configure()
    {
        AllowNullCollections = true;
        AllowNullDestinationValues = true;

        // calling non-static CreateMap
        CreateMap<User, DAL.Models.User>();
        CreateMap<DAL.Models.User, User>();
        CreateMap<Role, DAL.Models.Role>();
        CreateMap<DAL.Models.Role, Role>();
        CreateMap<Task, DAL.Models.Task>();
        CreateMap<DAL.Models.Task, Task>();
        CreateMap<TaskReport, DAL.Models.TaskReport>();
        CreateMap<DAL.Models.TaskReport, TaskReport>();
        CreateMap<Project, DAL.Models.Project>();
        CreateMap<DAL.Models.Project, Project>();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.