asp.net-mvc Automapper 缺少类型映射配置或不受支持的映射?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14677889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Automapper missing type map configuration or unsupported mapping?
提问by AliR?za Ad?yah?i
Entity Model
实体模型
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; }
}
CreateMap
创建地图
Mapper.CreateMap<CategoriesViewModel, Categoies>()
.ForMember(c => c.CategoryPositions, option => option.Ignore())
.ForMember(c => c.Posts, option => option.Ignore());
Map
地图
[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);
}
}
And Error
和错误
Missing type map configuration or unsupported mapping. Mapping types: CategoriesViewModel -> Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D NewsCMS.Areas.Admin.Models.CategoriesViewModel -> System.Data.Entity.DynamicProxies.Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D
Destination path: Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D
Source value: NewsCMS.Areas.Admin.Models.CategoriesViewModel
缺少类型映射配置或不受支持的映射。映射类型:CategoriesViewModel - > Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D NewsCMS.Areas.Admin.Models.CategoriesViewModel - > System.Data.Entity.DynamicProxies.Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D
目标路径:Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D
源值:NewsCMS.Areas.Admin.Models.CategoriesViewModel
What am I missing? I try to find, but I cant see problem.
我错过了什么?我试图找到,但我看不到问题。
UPDATE
更新
I have specified in application_start in Global.asax
我已经在 Global.asax 中的 application_start 中指定了
protected void Application_Start()
{
InitializeAutoMapper.Initialize();
}
InitializeClass
初始化类
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());
}
}
采纳答案by AliR?za Ad?yah?i
I found the solution, Thanks all for reply.
我找到了解决方案,谢谢大家的回复。
category = (Categoies)AutoMapper.Mapper.Map(viewModel, category, typeof(CategoriesViewModel), typeof(Categoies));
But, I have already dont know the reason. I cant understand fully.
但是,我已经不知道原因了。我无法完全理解。
回答by Martin4ndersen
Where have you specified the mapping code (CreateMap)? Reference: Where do I configure AutoMapper?
您在何处指定了映射代码 (CreateMap)?参考:在哪里配置 AutoMapper?
If you're using the static Mapper method, configuration should only happen once per AppDomain. That means the best place to put the configuration code is in application startup, such as the Global.asax file for ASP.NET applications.
如果您使用的是静态 Mapper 方法,则每个 AppDomain 只应进行一次配置。这意味着放置配置代码的最佳位置是应用程序启动,例如 ASP.NET 应用程序的 Global.asax 文件。
If the configuration isn't registered before calling the Map method, you will receive Missing type map configuration or unsupported mapping.
如果在调用 Map 方法之前没有注册配置,您将收到 Missing type map configuration or unsupported mapping.
回答by Pierry
In your class AutoMapperprofile, you need to create a map for your entity and viewmodel.
在您的类AutoMapper配置文件中,您需要为实体和视图模型创建映射。
ViewModel To Domain Model Mappings:
ViewModel 到域模型映射:
This is usually in AutoMapper/DomainToViewModelMappingProfile
这通常在 AutoMapper/DomainToViewModelMappingProfile
In Configure(), add a line like
在Configure(),添加一行
Mapper.CreateMap<YourEntityViewModel, YourEntity>();
Domain Model To ViewModel Mappings:
域模型到 ViewModel 映射:
In ViewModelToDomainMappingProfile, add:
在ViewModelToDomainMappingProfile,添加:
Mapper.CreateMap<YourEntity, YourEntityViewModel>();
回答by Darin Dimitrov
Notice the Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84Dclass 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:
注意到Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D异常中的类了吗?那是一个实体框架代理。我建议您处理您的 EF 上下文,以确保您的所有对象都急切地从数据库加载并且不存在此类代理:
[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.
如果实体检索在数据访问层内执行(这当然是正确的方法),请确保在从 DAL 返回实例之前处理 EF 上下文。
回答by Sanchitos
I did this to remove the error:
我这样做是为了消除错误:
Mapper.CreateMap<FacebookUser, ProspectModel>();
prospect = Mapper.Map(prospectFromDb, prospect);
回答by neustart47
Check your Global.asax.cs file and be sure that this line be there
检查您的 Global.asax.cs 文件并确保此行在那里
AutoMapperConfig.Configure();
回答by Mitchell Schwitzer
I know this is a rather old question as of now, but I had found the proper solution was that I was not declaring the assembly attribute.
我知道这是一个相当古老的问题,但我发现正确的解决方案是我没有声明程序集属性。
My code is:
我的代码是:
using AutoMapper;
...
namespace [...].Controllers
{
public class HousingTenureTypesController : LookupController<HousingTenureType, LookupTypeModel>
{
Mapper.CreateMap<HousingTenureType, LookupTypeModel>().ReverseMap();
}
...
}
This was fixed by adding the following line before my namespace declaration:
这是通过在我的命名空间声明之前添加以下行来解决的:
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(HousingTenureTypesController), "AutoMapperStart")]
The full code is:
完整代码是:
using AutoMapper;
...
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(HousingTenureTypesController), "AutoMapperStart")]
namespace [...].Controllers
{
public class HousingTenureTypesController : LookupController<HousingTenureType, LookupTypeModel>
{
Mapper.CreateMap<HousingTenureType, LookupTypeModel>().ReverseMap();
}
...
}
回答by Anand
Upgrade Automapper to version 6.2.2. It helped me
将 Automapper 升级到 6.2.2 版。它帮助了我
回答by Waldron
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:
我创建了一个新的 AutomapperProfile 类。它扩展了 Profile。我们的解决方案中有 100 多个项目。许多项目都有一个 AutomapperProfile 类,但这个是现有项目的新项目。但是,我确实找到了为我们解决这个问题必须做的事情。有一个绑定项目。在初始化中有这样的代码:
var mappingConfig = new List<Action<IConfiguration>>();
// Initialize the Automapper Configuration for all Known Assemblies
mappingConfig.AddRange( new List<Action<IConfiguration>>
{
ConfigureProfilesInAssemblyOfType<Application.Administration.AutomapperProfile>,
//...
I had to add ConfigureProfilesInAssemblyOfType<MyNewNamespace.AutomapperProfile>
我不得不添加 ConfigureProfilesInAssemblyOfType< MyNewNamespace.AutomapperProfile>
Note that ConfigureProfilesInAssemblyOfType looks like this:
请注意,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 );
} );
}
Best regards, -Jeff
最好的问候,-杰夫

