使用AutoMapper映射未知类型 [英] Using AutoMapper to map unknown types

查看:104
本文介绍了使用AutoMapper映射未知类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 AutoMapper 将一个对象的属性复制到另一个对象:这是我的代码:

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();

问题是 Mapper.Map()抛出 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?

推荐答案

您需要使用 Map 的非通用重载:

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

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

原因是您当前使用的通用版本未使用实例的运行时类型你过关了。而是使用编译时间类型- item 的编译时间类型为 object ,因为这是 Activator.CreateInstance

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.

这篇关于使用AutoMapper映射未知类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆