【问题标题】:How to map only properties from input? [duplicate]如何仅映射输入中的属性? [复制]
【发布时间】:2020-06-13 14:47:44
【问题描述】:

我想将Input 类映射到Output 类,但我不想重置Output 中不在Input 中的属性。

例如:

    public class Input
    {
        public string Name { get; set; }
    }    


    public class Output
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public async Task Update(int id, Input input)
    {
        var output = await _repository.GetById(id);

        ////////////////////////////
        // output.Id = 1;         //
        // output.Name = "Test";  //
        ////////////////////////////

        if (output != null)
        {
            output = _mapper.Map<Output>(input);

            // output.Id = 0 <------- I'd like to keep "1";

            _mainRepository.Update(output);
        }
    }

我想保持 Id=1。 AutoMapper可以吗?

我正在尝试使用 Ignore,但它不起作用:

    public PlayerProfile()
    {
        CreateMap<PlayerInput, PlayerOutput>()
            .ForMember(src => src.PlayerId, opt => opt.Ignore())
            .ForMember(src => src.Name, opt => opt.MapFrom(src => src.Name));
    }

【问题讨论】:

标签: c# .net .net-core mapping automapper


【解决方案1】:

尝试使用Map 方法的不同重载。

_mapper.Map&lt;Input, Output&gt;(input, output);_mapper.Map(input, output); 映射到现有的。

【讨论】:

    猜你喜欢
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 2012-04-01
    • 2020-01-17
    相关资源
    最近更新 更多