使用AutoMapper映射DTO后,Id字段变为0

时间:2019-06-30 11:26:25

标签: c# automapper

请在下面找到代码:

public class CustomerDto
{  
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public String Name { get; set; }
}

public class Customer
{  
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public String Name { get; set; }
}

// ...

var customers = _context.Customers.ToList();
var cusDtos= Mapper.Map<List<Customer>,List<CustomerDto>>(customers);
return cusDtos;

cusDtos中的所有对象都具有除Id以外的所有属性的值,Id的所有对象均为0。客户包含Id的价值,但映射后Id变为0。 谁能帮我解决这个问题?

谢谢。

2 个答案:

答案 0 :(得分:0)

您是否尝试过更改此代码

var cusDtos= Mapper.Map<List<Customer>,List<CustomerDto>>(customers);

对此进行更改

var cusDtos= Mapper.Map<List<CustomerDto>>(customers);

并找到自动映射器配置文件。并更改

 CreateMap<Customer, CustomerDto>()
         .ForMember(m => m.Id, opt => opt.Ignore());

对此

 CreateMap<Customer, CustomerDto>();

答案 1 :(得分:-1)

AutoMapper配置:

CreateMap<Customer, CustomerDto>();

您的代码:

var customers = _context.Customers.ToList();
var cusDtos = customers.Select(x => AutoMapper.Mapper.Map<CustomerDto>(x)).ToList();
return cusDtos;