AutoMapper 问题 - 列表无法映射

标签 automapper

我有以下类(class):

public class Account
{
    public int AccountID { get; set; }
    public Enterprise Enterprise { get; set; }
    public List<User> UserList { get; set; }
}

我有以下方法片段:

Entities.Account accountDto = new Entities.Account();
DAL.Entities.Account account;

Mapper.CreateMap<DAL.Entities.Account, Entities.Account>();
Mapper.CreateMap<DAL.Entities.User, Entities.User>();

account = DAL.Account.GetByPrimaryKey(this.Database, primaryKey, withChildren);

Mapper.Map(account,accountDto);
return accountDto;

调用该方法时,Account 类会正确映射,但 Account 类中的用户列表不会正确映射(为 NULL)。列表中有四个应映射的用户实体。有人可以告诉我可能出了什么问题吗?

最佳答案

尽量不要传入 accountDto,让 AutoMapper 为您创建它。当您映射到现有目标对象时,AutoMapper 会做出一些假设,即您不会有任何已经为空的目标集合。相反,请执行以下操作:

var accountDto = Mapper.Map<DAL.Entities.Account, Entities.Account>(account);

您应该检查的最后一件事是您的配置是否有效,因此您可以尝试:

Mapper.AssertConfigurationIsValid();

在这些 CreateMap 调用之后。这会检查以确保所有内容在目标类型方面正确排列。

关于AutoMapper 问题 - 列表无法映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2444522/

相关文章:

c# - 通过 AutoMapper 映射获取相关数据?

.net - 使用 AutoMapper 根据鉴别器值从不同属性进行映射

c# - 如果源类型和目标类型相同,我们是否需要使用asp.net Auto Mapper

c# - 如何替换 AutoMapper 9.0 中的 `AutoMapper.Mapper.Initialize` 静态调用?

dependency-injection - Automapper 和依赖注入(inject)

c# - AutoMapper 给出无效操作异常

c# - 在 AutoMapper 中使用上下文值进行投影

c# - AutoMapper - 一对多映射

c# - 仅当目标属性不为 null 时才使用 DestinationValue