Automapper missing type map configuration or unsupported mapping - Error

实体模型

public partial class Categoies
{
public Categoies()
{
this.Posts = new HashSet<Posts>();
}


public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Nullable<int> PositionId { get; set; }


public virtual CategoryPositions CategoryPositions { get; set; }
public virtual ICollection<Posts> Posts { get; set; }
}

View Model

public class CategoriesViewModel
{
public int Id { get; set; }


[Required(ErrorMessage = "{0} alanı boş bırakılmamalıdır!")]
[Display(Name = "Kategori Adı")]
public string Name { get; set; }


[Display(Name = "Kategori Açıklama")]
public string Description { get; set; }


[Display(Name = "Kategori Pozisyon")]
[Required(ErrorMessage="{0} alanı boş bırakılmamalıdır!")]
public int PositionId { get; set; }
}

创意地图

Mapper.CreateMap<CategoriesViewModel, Categoies>()
.ForMember(c => c.CategoryPositions, option => option.Ignore())
.ForMember(c => c.Posts, option => option.Ignore());

地图

[HttpPost]
public ActionResult _EditCategory(CategoriesViewModel viewModel)
{
using (NewsCMSEntities entity = new NewsCMSEntities())
{
if (ModelState.IsValid)
{
try
{
category = entity.Categoies.Find(viewModel.Id);
AutoMapper.Mapper.Map<CategoriesViewModel, Categoies>(viewModel, category);
//category = AutoMapper.Mapper.Map<CategoriesViewModel, Categoies>(viewModel);
//AutoMapper.Mapper.Map(viewModel, category);
entity.SaveChanges();


// Veritabanı işlemleri başarılı ise yönlendirilecek sayfayı
// belirleyip ajax-post-success fonksiyonuna gönder.
return Json(new { url = Url.Action("Index") });
}
catch (Exception ex)
{


}
}


// Veritabanı işlemleri başarısız ise modeli tekrar gönder.
ViewBag.Positions = new SelectList(entity.CategoryPositions.ToList(), "Id", "Name");
return PartialView(viewModel);
}
}

错误

缺少类型映射配置或不支持映射。 映射类型: 类别视图模型-> 类别 _ 7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D 类别 _ 7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D

目的地路线: Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D

来源价值: 区域。管理。模型。类别视图模型

What am I missing? I try to find, but I cant see problem.

更新

我已经在 Global.asax 的 application _ start 中指定了

protected void Application_Start()
{
InitializeAutoMapper.Initialize();
}

初始化类

public static class InitializeAutoMapper
{
public static void Initialize()
{
CreateModelsToViewModels();
CreateViewModelsToModels();
}


private static void CreateModelsToViewModels()
{
Mapper.CreateMap<Categoies, CategoriesViewModel>();
}


private static void CreateViewModelsToModels()
{
Mapper.CreateMap<CategoriesViewModel, Categoies>()
.ForMember(c => c.CategoryPositions, option => option.Ignore())
.ForMember(c => c.Posts, option => option.Ignore());
}
}
308221 次浏览

您在哪里指定了映射代码(CreateMap) ? 参考文献: 在哪里配置 AutoMapper?

如果您使用的是静态 Mapper 方法,那么每个 AppDomain 应该只进行一次配置。这意味着将配置代码放置在应用程序启动时的最佳位置,例如 ASP.NET 应用程序的 Global.asax 文件。

如果在调用 Map 方法之前没有注册配置,您将收到 Missing type map configuration or unsupported mapping.

Notice the Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D class in the exception? That's an Entity Framework proxy. I would recommend you disposing of your EF context to ensure that all your objects are eagerly loaded from the database and no such proxies exist:

[HttpPost]
public ActionResult _EditCategory(CategoriesViewModel viewModel)
{
Categoies category = null;
using (var ctx = new MyentityFrameworkContext())
{
category = ctx.Categoies.Find(viewModel.Id);
}
AutoMapper.Mapper.Map<CategoriesViewModel, Categoies>(viewModel, category);
//category = AutoMapper.Mapper.Map<CategoriesViewModel, Categoies>(viewModel, category);
entity.SaveChanges();
}

If the entity retrieval is performed inside a data access layer (which of course is the correct way) make sure you dispose your EF context before returning instances from your DAL.

我找到解决办法了,谢谢大家的回复。

category = (Categoies)AutoMapper.Mapper.Map(viewModel, category, typeof(CategoriesViewModel), typeof(Categoies));

但是,我已经不知道原因。我不能完全理解。

我这样做是为了消除这个错误:

Mapper.CreateMap<FacebookUser, ProspectModel>();
prospect = Mapper.Map(prospectFromDb, prospect);

在类 AutoMapper配置文件中,您需要为您的实体和视图模型创建一个映射。

ViewModel To Domain Model Mappings:

这通常是在 AutoMapper/DomainToViewModelMappingProfile

Configure()中,添加类似于

Mapper.CreateMap<YourEntityViewModel, YourEntity>();

域模型到视图模型映射:

ViewModelToDomainMappingProfile中,添加:

Mapper.CreateMap<YourEntity, YourEntityViewModel>();

举个例子

到目前为止,我知道这是一个相当古老的问题,但是我发现正确的解决方案是不声明程序集属性。

我的代码是:

using AutoMapper;
...


namespace [...].Controllers
{
public class HousingTenureTypesController : LookupController<HousingTenureType, LookupTypeModel>
{
Mapper.CreateMap<HousingTenureType, LookupTypeModel>().ReverseMap();
}
...
}

通过在我的名称空间声明之前添加以下代码行,这个问题得到了解决:

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(HousingTenureTypesController), "AutoMapperStart")]

完整代码是:

using AutoMapper;
...


[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(HousingTenureTypesController), "AutoMapperStart")]


namespace [...].Controllers
{
public class HousingTenureTypesController : LookupController<HousingTenureType, LookupTypeModel>
{
Mapper.CreateMap<HousingTenureType, LookupTypeModel>().ReverseMap();
}
...
}

检查 Global.asax.cs 文件,确保有这一行

 AutoMapperConfig.Configure();

升级自动化程序到6.2.2版本。它帮助了我

I created a new AutomapperProfile class. It extends Profile. We have over 100 projects in our solution. Many projects have an AutomapperProfile class, but this one was new to this existing project. However, I did find what I had to do to fix this issue for us. There is a Binding project. Within the Initialization there is this code:

var mappingConfig = new List<Action<IConfiguration>>();


// Initialize the Automapper Configuration for all Known Assemblies
mappingConfig.AddRange( new List<Action<IConfiguration>>
{
ConfigureProfilesInAssemblyOfType<Application.Administration.AutomapperProfile>,
//...

我不得不说 ConfigureProfilesInAssemblyOfType < MyNewNamespace.AutomapperProfile >

注意,ConfigureProfilesInAssemblyOfType 看起来是这样的:

    private static void ConfigureProfilesInAssemblyOfType<T>( IConfiguration configuration )
{
var log = LogProvider.Get( typeof (AutomapperConfiguration) );


// The Automapper Profile Type
var automapperProfileType = typeof (Profile);


// The Assembly containing the type
var assembly = typeof (T).Assembly;
log.Debug( "Scanning " + assembly.FullName );


// Configure any Profile classes found in the assembly containing the type.
assembly.GetTypes()
.Where( automapperProfileType.IsAssignableFrom ).ToList()
.ForEach( x =>
{
log.Debug( "Adding Profile '" + x.FullName + "'" );
configuration.AddProfile( Activator.CreateInstance( x ) as Profile );
} );
}

最好的问候, -Jeff

我也有同样的问题。网络核心。因为我的基 dto 类(我在自动装配程序程序集的启动时将它作为一个类型给出)在不同的项目中。Automapper 尝试在基类项目中搜索概要文件。但我的 DTO 是在不同的项目。我把基础课改了。问题解决了。这可能对某些人有帮助。

在我的例子中,我已经创建了映射,但是缺少了反向映射功能。添加它消除了错误。

      private static void RegisterServices(ContainerBuilder bldr)
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new CampMappingProfile());
});
...
}




public CampMappingProfile()
{
CreateMap<Talk, TalkModel>().ReverseMap();
...
}

我试图将 IEnumable 映射到一个对象。这就是我得到这个错误的方法。也许它有帮助。

我们得到了同样的错误后,更新自动绘图器第3节到第5节。

最后,我们发现目标类具有 IDictionary < string,object > 类型的 Property,并且在同一类型 Profile 映射是有效的。

还有下一种可能的解决方案:

  1. 升级到更高版本。在6节中,漏洞消失了。
  2. 或者忽略地图中的道具。
  3. 或者使用方法 Mapper.Map<IFooDto>(foo) instead of Mapper.Map(foo, fooDto).

我们的侧写是这样的,使用界面作为目的地:

public class FooProfile : Profile
{
public FooProfile()
{
CreateMap<Foo, IFooDto>()
.ConstructUsing(foo => new FooDto());
}
}

我还要提到的是,在从 v.3升级到更高版本的过程中,我们遇到了许多 bug 和与旧版本相比的不同之处,以及对我们有所帮助的地方:

  • 每次检查,也许下一个版本将修复错误;
  • 再次检查现有的 Mapping 配置。它可能有一些旧的隐藏 bug,比如没有 setter 的属性映射或现有的重复映射等等。可能旧版本允许这样,新版本不允许。

对于. net core 的依赖注入,我是这样设计的:

builder.Services.AddAutoMapper(config =>
{
config.CreateMap<CaseModel, Case>();
config.CreateMap<Case, CaseModel>();
}, AppDomain.CurrentDomain.GetAssemblies());

在这种情况下,每个具有映射的映射器实例都具有此映射配置。

Mapper 用户类:

public CaseController(ICaseHttpClient caseHttpClient, IMapper mapper)
{
_caseHttpClient = caseHttpClient;
_mapper = mapper;
}


[HttpGet("{id}")]
public async Task<ActionResult<CaseModel>> GetById(string id)
{
var caseResult = await _caseHttpClient.GetCase(id);
var caseModelMapped = _mapper.Map<CaseModel>(caseResult);
return Ok(caseModelMapped);
}

希望能有所帮助。

I have solved it hope it helps you :33

对于相同的 类型,你必须使用:

[AutoMap(typeof(UserInfoView))]

[AutoMap(typeof(UserInfoView))]