简体   繁体   English

如何在.Net core 2.2中为自定义属性配置AutoMapper?

[英]How to configure AutoMapper in .Net core 2.2 for custom properties?

I'm setting up AutoMapper for my Asp.Net core 2.2 application. 我正在为我的Asp.Net核心2.2应用程序设置AutoMapper。 How to configure this for custom properties? 如何为自定义属性配置?

-> Added "AutoMapper.Extensions.Microsoft.DependencyInjection (6.0.0)" NuGet package to the solution. - >将“AutoMapper.Extensions.Microsoft.DependencyInjection(6.0.0)”NuGet包添加到解决方案中。

-> Added "services.AddAutoMapper();" - >添加了“services.AddAutoMapper();” to "ConfigureServices" method in my startup.cs file. 在我的startup.cs文件中的“ConfigureServices”方法。

Mapping profile file: 映射配置文件:

    using AutoMapper;

    namespace Api.AutoMapperProfiles
    {
        public class MappingProfile : Profile
        {
            public MappingProfile()
            {
                var map = CreateMap<System.Data.DataRow, OneViewModel>();
                map.ForAllOtherMembers(opt => opt.Ignore());
                map.ForMember(d => d.one, o => o.MapFrom(s => s["one"]));
                map.ForMember(d => d.two, o => o.MapFrom(s => s["two"]));
            }
        }
    }

Controller file: 控制器文件:

  List<OneViewModel> pr = _mapper.Map<IDataReader, List<OneViewModel>>(ds.Tables[0].CreateDataReader());

I expect a list of "OneViewModel" from the datatable. 我希望数据表中有一个“OneViewModel”列表。 But I get an error that "Capacity" property is not mapped. 但是我收到一个错误,即“容量”属性未映射。 And there is not capacity property in my datatable or model. 并且我的数据表或模型中没有容量属性。

In your MappingProfile, you are configuring the mapping for System.Data.DataRow to OneViewModel . 在MappingProfile中,您将System.Data.DataRow的映射配置为OneViewModel What you should be configuring is, IDataReader to OneViewModel . 您应该配置的是IDataReaderOneViewModel

// configure mapping, hope you get the idea
var map = Mapper.CreateMap<IDataReader, CustomerModel>()
  .ForMember(dest => dest.one,
      opt => opt.MapFrom(src => src.GetValue(src.GetOrdinal("one")).ToString())))

// use
using (DataTableReader dr = ds.Tables[0].CreateDataReader())
{
    if (dr.HasRows)
    {
       var pr = AutoMapper.Mapper.Map<IDataReader, IList<OneViewModel>>(dr);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM