如何仅映射输入的属性?

问题描述 投票:-1回答:1

我想将Input类映射到Output类,但是我不想重置OutputInput中没有的属性。

例如:

    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个回答
-1
投票

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

_mapper.Map<Input, Output>(input, output);

© www.soinside.com 2019 - 2024. All rights reserved.