简体   繁体   English

Automapper null集合变为空

[英]Automapper null collection becomes empty

Why does automapper create empty instances of collections if they are null? 为什么automapper如果为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: 在我在Global.asax的MVC项目中,我只是添加我的个人资料:

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. 由于对Mapper.CreateMap方法的静态调用,您收到此错误。 If you change your code to just call the non static CreateMap method you should be good. 如果您将代码更改为只调用非静态CreateMap方法,那么您应该很好。

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>();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM