Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AutoMapper to map unknown types

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?

like image 815
Joel Avatar asked Feb 18 '13 15:02

Joel


1 Answers

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.

like image 154
Daniel Hilgarth Avatar answered Oct 07 '22 15:10

Daniel Hilgarth