Using AutoMapper to map unknown types

一世执手 提交于 2019-12-19 05:35:06

问题


I'm using AutoMapper to copy the properties of one object to another: This is my code:

// Get type and create first object
Type itemType = Type.GetType(itemTypeName);
var item = Activator.CreateInstance(itemType);

// Set item properties
.. Code removed for clarity ..

// Get item from Entity Framework DbContext
var set = dataContext.Set(itemType);
var itemInDatabase = set.Find(id);
if (itemInDatabase == null)
{
    itemInDatabase = Activator.CreateInstance(itemType);
    set.Add(itemInDatabase);
}

// Copy item to itemInDatabase
Mapper.CreateMap(itemType, itemType);
Mapper.Map(item, itemInDatabase);

// Save changes
dataContext.SaveChanges();

The problem is that Mapper.Map() throws an AutoMapperMappingException:

Missing type map configuration or unsupported mapping.

Mapping types:
Object -> MachineDataModel
System.Object -> MyProject.DataModels.MachineDataModel

Destination path:
MachineDataModel

Source value:
MyProject.DataModels.MachineDataModel

I don't really understand what the problem is, and what can I do to fix it?


回答1:


You need to use the non-generic overload of Map:

Mapper.Map(item, itemInDatabase, item.GetType(), itemInDatabase.GetType());

The reason is that the generic version you are currently using doesn't use the runtime type of the instances you pass. Rather it uses the compile time type - and the compile time type of item is object because that's the return value of Activator.CreateInstance.



来源:https://stackoverflow.com/questions/14939648/using-automapper-to-map-unknown-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!