AutoMapper没有按预期工作
本文关键字:工作 AutoMapper | 更新日期: 2023-09-27 18:18:16
我在我的域层有一个类,如下所示:
public class Employee : AuditableEntity
{
public string FirstName { get; set; }
public string Surname { get; set; }
public double Salary{ get; set; }
public int PhoneNo { get; set; }
public double Bonus
{
get { return Salary + EmployeeAdditionals.Sum(e => e.Value); }
}
// virtual allow lazy loading
public virtual ReadOnlyCollection<EmployeeAdditional> EmployeeAdditionals { get; private set; }
// Paramterless constructor for EF
public Employee()
{
EmployeeAdditionals = new List<EmployeeAdditional>();
}
public void AddAdditionalInfo(EmployeeAdditional additionalInfo)
{
additionalInfo.Employee = this;
additionalInfo.EmployeeId = Id;
((Collection<EmployeeAdditional>) EmployeeAdditionals).Add(additionalInfo);
}
然后我有以下viewModel类在我的MVC 5应用程序:
public class EmployeeDetailsViewModel : BaseViewModel
{
public EmployeeDetailsViewModel()
{
Employee = new Employee();
}
public Employee Employee { get; set; }
//Other fields
}
public class Employee
{
[DisplayName("Employee First Name")]
public string FirstName { get; set; }
[DisplayName("Employee Surname")]
public string Surname{ get; set; }
public double Salary{ get; set; }
[RegEx for Phone Number and Error Mesage]
public int PhoneNo{ get; set; }
public double Bonus { get; set; }
}
我有映射,然后在我的控制器和viewModel构建器映射我的视图模型到我的域模型和域模型回视图模型,我试图使用AutoMapper对此。
像下面这样使用手动映射:
// set domain from viewModel
employee.FirstName= model.Employee.FirstName;
//etc for rest of fields
// set view model from domain
viewModel.Employee.FirstName = employee.FirstName;
//etc for rest of fields
现在在我的AutoMapperBootstrapper类的Setup方法中,我有以下内容:
Mapper.CreateMap<Domain.Models.Employee, Employee>();
Mapper.CreateMap<Employee, Domain.Models.Employee>();
然后我使用这是以下在我的控制器和视图模型构建器:
//set domain from viewModel
Mapper.Map(employee, model.Employee);
// set viewmodel from domain
Mapper.Map(viewModel.Employee, employee);
当我在从域到viewModel的映射上遇到断点时,我看到了模型。Employee与屏幕上的值,但是当我跨过这条线时,值没有映射到域Employee,然后映射到模型。对于字符串,employee值被重置为null,对于double值被重置为0.0,等等。
我的配置或使用automapper是否有问题?
您传递错误的参数。如果您想使用现有实例,请确保第一个参数为source,第二个参数为destination。
尝试切换参数
//set domain from viewModel (viewModel is the source)
Mapper.Map(model.Employee, employee);
^^^^^ ^^^^^
source destination
// set viewmodel from domain (domain is the source)
Mapper.Map(employee, viewModel.Employee);
^^^^^ ^^^^^
source destination
你的地图代码不应该是这样的吗?你必须使用Map()
的实例,看起来你在使用Types
//set domain from viewModel
Mapper.Map(viewEmployee, new model.Employee());
// set viewmodel from domain
Mapper.Map( employee, new viewmodel.Employee());
我希望你这样使用它:
var viewModel = Mapper.Map<ViewModel.Employee>(domainModel); <-- this creates a ViewModel for a Domain Model
,反之为
var domainModel = Mapper.Map<Domain.Employee>(viewModel);