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!
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>();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.