将同名字段映射到自动映射器中的不同字段 [英] Map fields with same name to different fileds in automapper

查看:14
本文介绍了将同名字段映射到自动映射器中的不同字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,我试图从 .net core 2.0 中的 Match 类映射该模型.这两个类都有一个 Name 属性.

I have a model which I am trying to map from Match class in .net core 2.0. Both the classes have a Name property.

我需要映射 Match.Value => ViewCompany.Name

但它总是将 Match.Name 放入 ViewCompany.Name

这是我的AutomapperProfile:

CreateMap<Match, ViewCompany>()
                .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Value));

.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Value))

.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Value))

查看公司:

public class ViewCompany
{
    public ViewCompany()
    {

    }

    public ViewCompany(string name)
    {
        this.Name = name;
    }

    public int Id { get; set; }

    public string Name { get; set; }
}

上面的映射不起作用.

但是,如果我将模型中的属性名称更改为Value"或tempName"等其他名称并更新自动映射器配置文件,则它可以正常工作.

But if I change property name in the model to something else like "Value" or "tempName" and update the automapper profile, it works fine.

那么,Automapper 中不能将同名的属性映射到不同的属性吗?

So, is it not possible to map properties with same names to different properties in Automapper?

推荐答案

这里发生的事情是 Name 是通过 构造函数.避免这种情况的一个简单方法是告诉 AM 要使用什么构造函数:

What happens here is that Name is mapped through the constructor. A simple way to avoid that is to tell AM what constructor to use:

 CreateMap<Match, ViewCompany>().ConstructUsing(source=>new ViewCompany());

这篇关于将同名字段映射到自动映射器中的不同字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆