实体模型
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; }
}
查看模型
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());
地图
[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);
}
}
错误
缺少类型映射配置或不支持的映射。 映射类型: CategoriesViewModel - &gt; Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D NewsCMS.Areas.Admin.Models.CategoriesViewModel - &gt; System.Data.Entity.DynamicProxies.Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D
目的地路径: Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D
来源价值: NewsCMS.Areas.Admin.Models.CategoriesViewModel
我错过了什么?我试图找到,但我看不出问题。
更新
我已在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());
}
}
感谢。
答案 0 :(得分:54)
您在哪里指定了映射代码(CreateMap)?参考:Where do I configure AutoMapper?
如果您使用静态Mapper方法,则每个AppDomain只应进行一次配置。这意味着放置配置代码的最佳位置是应用程序启动,例如ASP.NET应用程序的Global.asax文件。
如果在调用Map方法之前未注册配置,您将收到Missing type map configuration or unsupported mapping.
答案 1 :(得分:18)
注意异常中的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();
}
如果实体检索是在数据访问层内执行的(当然这是正确的方法),请确保在从DAL返回实例之前处置EF上下文。
答案 2 :(得分:18)
在您的班级AutoMapper
个人资料中,您需要为您的实体和视图模型创建地图。
通常在AutoMapper/DomainToViewModelMappingProfile
在Configure()
中,添加一行
Mapper.CreateMap<YourEntityViewModel, YourEntity>();
在ViewModelToDomainMappingProfile
中,添加:
Mapper.CreateMap<YourEntity, YourEntityViewModel>();
答案 3 :(得分:6)
我这样做是为了删除错误:
Mapper.CreateMap<FacebookUser, ProspectModel>();
prospect = Mapper.Map(prospectFromDb, prospect);
答案 4 :(得分:4)
我找到了解决方案,谢谢大家的回复。
category = (Categoies)AutoMapper.Mapper.Map(viewModel, category, typeof(CategoriesViewModel), typeof(Categoies));
但是,我已经不知道原因了。我完全理解不了。
答案 5 :(得分:4)
检查您的Global.asax.cs文件并确保该行存在
AutoMapperConfig.Configure();
答案 6 :(得分:3)
.Net Core中存在相同的问题。因为我的基本dto类(我在启动时将其作为自动映射器程序集的一种类型)在其他项目中。 Automapper试图在基类项目中搜索配置文件。但是我的dto在不同的项目中。我搬了我的基础班。问题解决了。这可能对某些人有帮助。
答案 7 :(得分:1)
就我而言,我已经创建了地图,但是缺少了ReverseMap函数。添加它可以消除错误。
private static void RegisterServices(ContainerBuilder bldr)
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new CampMappingProfile());
});
...
}
public CampMappingProfile()
{
CreateMap<Talk, TalkModel>().ReverseMap();
...
}
答案 8 :(得分:1)
我试图将IEnumerable映射到对象。这是我收到此错误的方法。也许有帮助。
答案 9 :(得分:0)
我知道这是一个相当古老的问题,但我发现正确的解决方案是我没有声明汇编属性。
我的代码是:
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();
}
...
}
答案 10 :(得分:0)
将Automapper升级到版本6.2.2。它帮助了我
答案 11 :(得分:-1)
我创建了一个新的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>,
//...
我必须添加 ConfigureProfilesInAssemblyOfType << em> 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 );
} );
}
最好的问候, -杰夫