这可能是一个基本问题,但想知道我没有得到AutoMapper.Mapper.CreateMap方法。
我使用了错误的AutoMapper参考/软件包吗?谢谢
Answers:
该CreateMap
方法的静态版本在4.2中已弃用,然后在5.0版中从API中删除。吉米•鲍嘉(Jimmy Bogard)在博客中对此进行了详细讨论。
映射的新技术是非静态的,如下所示(代码来自帖子):
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Source, Dest>();
});
IMapper mapper = config.CreateMapper();
var source = new Source();
var dest = mapper.Map<Source, Dest>(source);
The type or namespace name 'MapperConfiguration' could not be found (are you missing a using directive or an assembly reference?)
,IMapper
请问您也可以帮我吗?
这是我在代码中使用AutoMapper的方式。
步骤1:通过nuget-packages下载了AutoMapper。
版本是
<package id="AutoMapper" version="6.1.1" targetFramework="net452" />
步骤1:创建DTO类
public class NotificationDTO
{
public DateTime DateTime { get; private set; }
public NotificationType Type { get; private set; }
public DateTime? OriginalDateTime { get; private set; }
public string OriginalVenue { get; private set; }
public ConcertDTO Concert { get; set; }
}
public class ConcertDTO
{
public int Id { get; set; }
public bool IsCancelled { get; private set; }
public DateTime DateTime { get; set; }
public string Venue { get; set; }
}
第2步:创建一个从Profile继承的AutoMapperProfile类
using AutoMapper;
using ConcertHub.DTOs;
namespace ConcertHub.Models
{
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<Concert, ConcertDTO>();
CreateMap<Notification, NotificationDTO>();
}
}
}
步骤3:在Global.asax文件的Application Start方法中注册AutoMapperProfile
protected void Application_Start()
{
AutoMapper.Mapper.Initialize(cfg => cfg.AddProfile<AutoMapperProfile>());
}
最后是Api控制器中神奇的代码
public IEnumerable<NotificationDTO> GetNewNotification()
{
var userId = User.Identity.GetUserId();
var notifications = _dbContext.UserNotifications
.Where(un => un.UserId == userId && !un.IsRead)
.Select(un => un.Notification)
.Include(n => n.Concert)
.ProjectTo<NotificationDTO>()//use Automapper.QueryableExtension namespace
.ToList();
return notifications;
}
希望能帮助到你 。
现在是这样工作的:
Mapper.Initialize(cfg =>
{
cfg.CreateMap<SupervisorEmployee, SupervisorViewModel>()
.ForMember
(dst => dst.Name, src => src.MapFrom<string>(e => SupervisorViewModel.MapName(e)))
.ForMember
(dst => dst.OfficePhone, src => src.MapFrom<string>(e => e.OfficePhone.FormatPhone(e.OfficePhoneIsForeign)))
.ForMember
(dst => dst.HomePhone, src => src.MapFrom<string>(e => e.HomePhone.FormatPhone(e.HomePhoneIsForeign)))
.ForMember
(dst => dst.MobilePhone, src => src.MapFrom<string>(e => e.MobilePhone.FormatPhone(e.MobilePhoneIsForeign)));
});