.net core中使用automapper

发布时间:2020-03-18 15:17:50来源:本站阅读(790)

    首先从NUGET上引入以下两个包

    AutoMapper 和 AutoMapper.Extensions.Microsoft.DependencyInjection

    AutoMapper.Extensions.Microsoft.DependencyInjection是配合注入的。

    然后,在项目中添加配置

    我是新建类MyProfile


    public class MyProfile:Profile
        {
            public MyProfile()
            {
            CreateMap<CreateOrderParams, CreateOrderPost>();
                CreateMap<CellOrderApiModel, CellOrderViewModel>().ConstructUsing(x => new CellOrderViewModel(x.Id,
                    x.UserId, x.UserName, x.GoodsType, x.GoodsNum, x.SinglePrice, x.AllPrice, x.PayType, x.OrderStat,
                    x.CreateTime.ToLong(), x.PayTime.HasValue ? x.PayTime.Value.ToLong() : 0,
                    x.CompleteTime.HasValue ? x.CompleteTime.Value.ToLong() : 0, x.ContractStat)).ForMember(x=>x.CreateTime,options=>options
                    .Ignore()).ForMember(x=>x.PayTime,opt=>opt.Ignore()).ForMember(x=>x.CompleteTime,opt=>opt.Ignore());
                CreateMap<AppointmentApiModel, AppointmentViewModel>().ConstructUsing(x =>
                    new AppointmentViewModel(x.CreateTime.ToLong(),
                        x.CancelTime.HasValue ? x.CancelTime.Value.ToLong() : 0));
                CreateMap<ContractApiModel, ContractViewModel>().ConstructUsing(x =>
                    new ContractViewModel(x.cRealname.HiddenName(), x.AdminDate.ToLong(), x.StartDate.ToLong(),
                        x.EndDate.ToLong()));
        }
    }

    注意需要继承Profile

    以上代码中有我用到的一些用法,供参考。

    最后在startup中

    services.AddAutoMapper(typeof(MyProfile));

    这样就可以了。

    当然,使用中还是有不少坑的。大家慢慢发现吧。


关键字automapper

上一篇: VUE环境搭建

下一篇: VUE新建项目