11

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 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Haha, I was gonna tell you to switch the order of the parameters, but you were too fast. But it works like a charm! I'll accept your answer as soon as I can.
@Joel: Yeah, I first wrote down the relevant parts and then looked up the correct ordering :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.