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!
The Null substitution allows us to supply an alternate value for a destination member if the source value is null. That means instead of mapping the null value from the source object, it will map from the value we supply.
AutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.
So, the AutoMapper Ignore() method is used when you want to completely ignore the property in the mapping. The ignored property could be in either the source or the destination object.
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>();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With