加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 没有CreateMap的简单转换时的Automapper错误

发布时间:2020-12-16 07:44:20 所属栏目:asp.Net 来源:网络整理
导读:我有这两个型号: public class SiteSettingsViewModel{ public decimal SubscriptionFee { get; set; }}public class SiteSettings{ public decimal SubscriptionFee { get; set; }} 和代码: var model = Mapper.MapSiteSettings,SiteSettingsViewModel(se
我有这两个型号:

public class SiteSettingsViewModel
{
    public decimal SubscriptionFee { get; set; }
}

public class SiteSettings
{
    public decimal SubscriptionFee { get; set; }
}

和代码:

var model = Mapper.Map<SiteSettings,SiteSettingsViewModel>(settingService.GetSettings());

这引发了以下错误:

Trying to map WebApp1.Domain.Site.SiteSettings to WebApp1.WebUI.ViewModel.SiteSettingsViewModel.
Missing type map configuration or unsupported mapping.
Exception of type ‘AutoMapper.AutoMapperMappingException’ was thrown.

为什么我需要输入代码:

Mapper.CreateMap<SiteSettings,SiteSettingsViewModel>();

对我来说,这似乎是我在编写猴子代码.这不是必需的.

为什么1号线不起作用?

解决方法

一个原因是它对于需要定义更具体行为的更复杂的映射方案很有用.例如(从 CodePlex):

Mapper.CreateMap<CalendarEvent,CalendarEventForm>()
    .ForMember(dest => dest.EventDate,opt => opt.MapFrom(src => src.EventDate.Date))
    .ForMember(dest => dest.EventHour,opt => opt.MapFrom(src => src.EventDate.Hour))
    .ForMember(dest => dest.EventMinute,opt => opt.MapFrom(src => src.EventDate.Minute));

像你正在做的简单映射的另一个选择是制作一个通用映射器,为你处理CreateMap调用,如下所示:

public interface IMapper<T1,T2>
{   
    T1 Map(T2 source);
}

public class Mapper<T1,T2> : IMapper<T1,T2> where T1 : class where T2 : class
{
    public Mapper()
    {
        Mapper.CreateMap<T2,T1>();
    }

    public T1 Map(T2 source)
    {
        return Mapper.Map<T2,T1>(source);
    }   
}

然后你可以直接实例化它们,如:

var mapper = new Mapper<SiteSettings,SiteSettingsViewModel>();

或者注册它们以注入您的控制器,或者您计划使用它们的任何其他地方.希望有所帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读