我真的在用Automapper。我觉得它不直观,而且很难使用。手动编写映射代码会容易得多。我有两种简单的类型:
namespace BusinessObjects
{
public class Application
{
public int ID { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public System.DateTime DateOfBirth { get; set; }
public System.DateTime CreatedTime { get; set; }
public System.DateTime ModifiedTime { get; set; }
public System.DateTime ApplicationDate { get; set; }
public string Qualified { get; set; }
public int salary { get; set; }
public string userID { get; set; }
}
}
namespace DataObjects
{
using System;
using System.Collections.Generic;
public partial class Application
{
public int ID { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public System.DateTime DateOfBirth { get; set; }
public System.DateTime CreatedTime { get; set; }
public System.DateTime ModifiedTime { get; set; }
public System.DateTime ApplicationDate { get; set; }
public string Qualified { get; set; }
public int salary { get; set; }
public string userID { get; set; }
}
}
和控制器:
public ApplicationController()
{
Mapper.Initialize(cfg => cfg.CreateMap<BusinessObjects.Application, ApplicationModel>());
config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<BusinessObjects.Application, ApplicationModel>();
});
config.AssertConfigurationIsValid();
Mapper.Initialize(cfg => cfg.CreateMap<ApplicationModel,BusinessObjects.Application>());
config2 = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ApplicationModel,BusinessObjects.Application>();
});
config2.AssertConfigurationIsValid();
}
public int Create(BusinessObjects.Application businessApplication)
{
var mapper =config2.CreateMapper();
DataObjects.Application dataApplication = AutoMapper.Mapper.Map<DataObjects.Application>(businessApplication);
int count = 0;
using (CreditCardPreQualificationEntities CreditCardPreQualificationDatabase = new CreditCardPreQualificationEntities())
{
CreditCardPreQualificationDatabase.Applications.Add(dataApplication);
count = CreditCardPreQualificationDatabase.SaveChanges();
}
return count;
}
我几乎花了整整一个周末的时间试图让它发挥作用,但并没有更接近。我根本看不出Automapper的好处。我得到的错误是:"在AutoMapper.dll中发生了类型为"AutoMapper.AutoMapperMappingException"的异常,但未在用户代码中处理
附加信息:缺少类型映射配置或不支持的映射。"请帮忙。
您的配置看起来。。。。正如文档所说,您需要为整个AppDomain初始化AutoMapper一次,而且只初始化一次。在您的global.asax(或类似的)中,添加:
Mapper.Initialize(cfg => {
cfg.CreateMap<BusinessObjects.Application, DataObjects.Application>()
.ReverseMap();
});
看起来你需要两个方向的贴图,所以我添加了ReverseMap。然后在你的控制器中,删除所有初始化和映射器创建垃圾,直接使用AutoMapper:
public int Create(BusinessObjects.Application businessApplication)
{
DataObjects.Application dataApplication = Mapper.Map<BusinessObjects.Application, DataObjects.Application>(businessApplication);
int count = 0;
using (CreditCardPreQualificationEntities CreditCardPreQualificationDatabase = new CreditCardPreQualificationEntities())
{
CreditCardPreQualificationDatabase.Applications.Add(dataApplication);
count = CreditCardPreQualificationDatabase.SaveChanges();
}
return count;
}
完成!