找到自动映射器未映射成员

我们在一个项目中使用了 Automapper,似乎随机得到了以下错误:

自动绘图软件。AutoMapperConfigurationException: 找到未映射的成员。查看下面的类型和成员。添加自定义映射表达式、忽略、添加自定义解析器或修改源/目标类型

密码已经好几个月没更改了。我得到那个错误,刷新,错误消失了,页面工作正常。我在吸毒

Mapper.AssertConfigurationIsValid();

不知道为什么它抱怨映射不好,然后刷新,再次罚款,有人遇到这个吗?调试没有帮助,因为它是随机的,有时没有错误,然后其他日子它会弹出在网站的某个地方,回到它和它的罚款。这个错误也会出现在随机的页面上,不是同一个页面,不是同一个映射。

89811 次浏览

Quick intro edit: as @mrTurkay answers below, this can be solved with the following configuration:

cfg.ValidateInlineMaps = false;

However, you should understand why the problem occours in the first place - so feel free to read on.

This problem occours when you're trying to map an object that you didn't create a mapping configuration for. What you need to keep in mind is, that it doesn't have to be the specific object you're trying to map; but one of it's navigation properties.

Say for instance you have a Car.cs that you want to map to a CarDTO.cs

The Car.cs looks like this:

public class Car
{
public string Color { get; set; }


public Engine Engine { get; set; }
}

And your DTO looks the same, but has a reference to the EngineDTO instead:

public class CarDTO
{
public string Color { get; set; }


public EngineDTO Engine { get; set; }
}

You configured the mapping like this:

    Mapper.CreateMap<DTO.CarDTO, Data.Model.Car>();
Mapper.CreateMap<Data.Model.Car, DTO.CarDTO>();


Mapper.CreateMap<DTO.EngineDTO, Data.Model.Engine>();
Mapper.CreateMap<Data.Model.Engine, DTO.EngineDTO>();

All looks fine, right? However, in your EngineDTO, you probably have a navigation property like, lets say:

public class EngineDTO
{
public List<PartDTO> Parts { get; set; }
}

So while Automapper is Mapping from Engine to EngineDTO, it also tries to Map the PartDTO, but since you forgot to declare the mapping in the global.asax, you get the error:

AutoMapper.AutoMapperConfigurationException: Unmapped members were found. Review the types and members below. Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type

If you don't want to map certain properties on a class, you can use Ignore:

Mapper.CreateMap<Engine, EngineDTO>()
.ForMember(x => x.Parts, opt => opt.Ignore());

EDIT:

For a more robust AutoMapper configuration, I suggest that you use mapping profiles, instead of declaring the mapping directly in Global.asax. Here is an Example:

Profile:

public class CarProfile : Profile
{
public CarProfile ()
{
CreateMap<Car, CarDTO>();
}
}

Global.asax:

Mapper.Initialize(cfg =>
{
cfg.AddProfile<CarProfile>();
}

it is about validation.

cfg.ValidateInlineMaps = false;

should be enough

In my case, I had forgotten to add Map Configuration to MapConfig.cs.