【问题标题】:After mapping DTO using AutoMapper, the Id field becomes 0使用 AutoMapper 映射 DTO 后,Id 字段变为 0
【发布时间】:2019-06-30 11:26:25
【问题描述】:

请在下面找到代码:

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。 谁能帮我解决这个问题?

提前致谢。

【问题讨论】:

  • 检查此Link 可能会有所帮助

标签: c# automapper


【解决方案1】:

您是否尝试过更改此代码

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>();

【讨论】:

    【解决方案2】:

    AutoMapper 配置:

    CreateMap<Customer, CustomerDto>();
    

    您的代码:

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

    【讨论】:

    • 欢迎您,但我不知道为什么我会投反对票?我一直使用这段代码,我知道它有效
    猜你喜欢
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多