【问题标题】:How to take the mapping fields in Automapper?如何在 Automapper 中获取映射字段?
【发布时间】:2020-03-01 10:26:54
【问题描述】:

我正在使用 Automapper。在那里,我创建了一个如下所示的自动映射器配置文件:

  public MappingProfile()
  {
      CreateMap<Users, UserDetails>()
            .ForMember(destination => destination.IsUser, options => options.MapFrom(src => src.RoleId == 1))
            .ForMember(o => o.UserId, b => b.MapFrom(z => z.Id))
            .ReverseMap();
  }

用户

public class Users
{
  public int Id { get; set; }
  public int RoleId { get; set; }
  public string Name { get; set; }
}

用户详情

public class UserDetails
{
   public int UserId { get;set; }
   public bool IsUser { get; set; }
   public string Name { get; set; }
}

在模型类User.cs 中,我需要获取映射字段。即)UserId 中的 UserDetails 映射自 Id 中的 Users 类。如何在自动映射器中采取这样的措施? (或)有没有其他方法可以采取这个?

【问题讨论】:

  • 你想做什么?
  • @LucianBargaoanu - 我需要检索映射的字段。
  • 这不能回答问题。

标签: c# mapping automapper


【解决方案1】:

解决办法:

在模型类User.cs

  private readonly IMapper mapper;


   var mappingFields = mapper.ConfigurationProvider.FindTypeMapFor(typeof(Users), typeof(UserDetails));
   var propertyMapList = mappingFields.PropertyMaps.ToList();

   foreach (var item in propertyMapList)
   {
       ----------------
       var mappingField = item.SourceMember.Name;  ---> Here, we get the source field name. i.e) Id
   }

这对我有用。

【讨论】:

    猜你喜欢
    • 2014-10-28
    • 1970-01-01
    • 2014-10-06
    • 2022-06-15
    • 1970-01-01
    • 2018-09-10
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多