【发布时间】: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