更新时间:2022-05-29 23:13:43
快速介绍如下面的@mrTurkay回答,可以通过以下配置解决此问题:
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.
例如,您有一个要映射到CarDTO.cs
Say for instance you have a Car.cs
that you want to map to a CarDTO.cs
Car.cs
看起来像这样:
public class Car
{
public string Color { get; set; }
public Engine Engine { get; set; }
}
和您的DTO看起来一样,但是引用了EngineDTO
:
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>();
一切看起来都很好,对吧?但是,在您的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; }
}
因此,当Automapper从Engine
映射到EngineDTO
时,它也会尝试映射PartDTO
,但是由于忘记了在global.asax
中声明映射,因此会出现错误:
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:未映射的成员是 成立.在下面查看类型和成员.添加自定义映射 表达式,忽略,添加自定义解析器或修改 来源/目的地类型
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());
对于更强大的AutoMapper配置,我建议您使用映射配置文件,而不是直接在Global.asax
中声明映射.这是一个示例:
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:
个人资料:
public class CarProfile : Profile
{
public CarProfile ()
{
CreateMap<Car, CarDTO>();
}
}
Global.asax:
Global.asax:
Mapper.Initialize(cfg =>
{
cfg.AddProfile<CarProfile>();
}