【问题标题】:item with existing key, when creating MappingConfiguration创建 MappingConfiguration 时具有现有密钥的项目
【发布时间】:2020-02-09 02:46:25
【问题描述】:
public class ClinicController
{
    private List<Employee> Employees;
    private List<Patient> Patients;
    private Mapper _objectMapper;

    public ClinicController()
    {
        Employees = new List<Employee>();
        Patients = new List<Patient>();
        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Doctor, DoctorDto>().ReverseMap();
            //cfg.CreateMap<Employee, Doctor>();
            //cfg.CreateMap<DoctorDto, Doctor>();
            //cfg.CreateMap<Employee, EmployeeDto>();
            //cfg.CreateMap<Patient, DoctorDto>();
        });
        _objectMapper = new Mapper(config);
    }
}

当我实例化这个类时,每当创建配置时,就会引发异常。它说:

"An item with the same key has already been added"

我一直在阅读具有相同问题的问题,但我似乎无法弄清楚问题所在。调试代码发现程序永远无法初始化 Mapper,它在初始化配置时就崩溃了。

我忽略了什么?

类:

public abstract class PersonDto
{
    public string Name { get; set; }
    public string Surnames { get; set; }
    public string Data{ get; set; }
    public string Email { get; set; }
    public string Telephone { get; set; }
    public string Direction { get; set; }
}
public abstract class Person
{
    public string Name { get; set; }
    public string Surnames { get; set; }
    public string Data { get; set; }
    public string Email { get; set; }
    public string Telephone { get; set; }
    public string Direction { get; set; }
}
public class Patient : Person
    {
        public string Service { get; set; }
        public float Pay { get; set; }
    }
    public class Employee : Person
    {
        public string Job { get; set; }
        public float Salary { get; set; }
    }
public class Doctor : Employee
{
    public new string Job = "Doctor";
}

这是与原始类具有相同属性的类(我没有包含这些方法,因为它们无关紧要)。 Dto 遵循与实体本身相同的结构。

【问题讨论】:

  • @John 你只需要创建一个新的类实例。我知道您还需要映射中使用的类,但是我不允许共享该代码。
  • 为什么不允许分享?当然,您可以使用相同的数据类型创建一个完全不相关的模型,但没有任何有意义的名称等?无论哪种方式,如果没有复制箱,我们将无法为您提供帮助。
  • @John 您描述的场景是正确的。我会和我的前辈谈谈。

标签: c# mapping automapper


【解决方案1】:

如果 Doctor DTO 也“覆盖”了 Job 属性,它会崩溃,因为会有 2 个 Job “Keys”。不要使用新字符串并找到另一种方法。 由于您将 Doctors 映射到他们的 DTO,因此不需要指定 Job 的值(假设它没有被修改并存储在 DB 中)。

【讨论】:

  • 刚刚测试过了。它有效,我什至没有想过在 DTO 上拥有该 Job 定义是多么无用。谢谢
猜你喜欢
  • 2016-03-25
  • 2011-03-15
  • 2012-12-25
  • 2011-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多