Sam*_*ami 78 asp.net-mvc automapper asp.net-web-api
这可能是一个基本问题,但我想知道我没有得到AutoMapper.Mapper.CreateMap方法.
我使用错误的AutoMapper参考/包吗?谢谢
Wil*_*Ray 110
该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);
Run Code Online (Sandbox Code Playgroud)
ksg*_*ksg 39
以下是我在代码中使用AutoMapper的方法.
第1步:通过nuget-packages下载AutoMapper.
版本是
<package id="AutoMapper" version="6.1.1" targetFramework="net452" />
Run Code Online (Sandbox Code Playgroud)
第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; }
}
Run Code Online (Sandbox Code Playgroud)
第2步:创建一个继承自Profile的AutoMapperProfile类
using AutoMapper;
using ConcertHub.DTOs;
namespace ConcertHub.Models
{
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<Concert, ConcertDTO>();
CreateMap<Notification, NotificationDTO>();
}
}
}
Run Code Online (Sandbox Code Playgroud)
步骤3:在Global.asax文件的Application Start方法中注册AutoMapperProfile
protected void Application_Start()
{
AutoMapper.Mapper.Initialize(cfg => cfg.AddProfile<AutoMapperProfile>());
}
Run Code Online (Sandbox Code Playgroud)
最后是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;
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你 .
Mic*_*l K 19
以下是它现在的工作原理:
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)));
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
53608 次 |
最近记录: |