Using AutoMapper to map unknown types

2020-03-11 03:21发布

问题:

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.