簡體   English   中英

帶有列表到列表的自動映射器映射異常

[英]Automapper mapping exception with lists to lists

我對 Automapper 有疑問。 我的映射調用如下所示:

var dataContracts = MapperManager.Mapper.Map<List<Employee>, List<EmployeeDTO>>(entities.ToList());

實體是IQueryable<Employee>

在我的 Mapper 助手 class 中,我有:

public class MapperManager
{
    public static MapperConfiguration MapperConfiguration { get; set; }

    private static IMapper _mapper { get; set; }

    public static IMapper Mapper
    {
        get
        {
            if (_mapper == null) {
                _mapper = MapperConfiguration.CreateMapper();                    
            }

            return _mapper;
        }
    }

    public static void RegisterMappinngs()
    {

        MapperConfiguration = new MapperConfiguration(cfg =>
        {
            ...
            cfg.CreateMap<Employee, EmployeeDTO>().MaxDepth(5);
            ...
        }
    }
}

RegisterMappings 在 Global.asax 中的 AppStartup 上被調用一次,之后我在 Map 操作中出現異常:

var dataContracts = MapperManager.Mapper.Map<List<Employee>, List<EmployeeDTO>>(entities.ToList());

錯誤映射類型。

映射類型:List`1 -> List`1 System.Collections.Generic.List`1[[NAMESPACE.Employee, ASSEMBLY, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic .List`1[[NAMESPACE2.EmployeeDTO, ASSEMBLY2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]

任何人都可以提供任何想法我做錯了什么?

最好的祝福

好的,這就是答案:

MapperConfiguration.AssertConfigurationIsValid()

當我調用它時,我得到了 AMConfigurationException 與未映射的屬性,在另一個 Employee 屬性的深處。

謝謝你的建議

就我而言,這是因為它試圖映射本應被忽略的 ID

我遇到了這個錯誤,我能夠在生產環境中運行它,但是單元測試失敗了,失敗了,失敗了。

如果您設置自己的映射器配置,請確保包含您的配置文件。 還要仔細檢查您的映射。

var mappingConfig = new MapperConfiguration(mc =>
        {
            mc.AddProfile(new MyMissingProfile());
        });
        
        _mapper = mappingConfig.CreateMapper();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM