请在下面找到代码:
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。
谁能帮我解决这个问题?
谢谢。
答案 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;