我有一个单元测试,我使用从Model到ViewModel的mapper,而ViewModel返回模型更新记录 - 但实际上我没有改变一件事,只是测试更新是否有效。
[TestMethod]
public void UpdateEntry()
{
//Map Model to ViewModel
Mapper.CreateMap<GlobalExport, GlobalExportViewModel>();
Mapper.CreateMap<FileNameSetup, FileNameSetupViewModel>();
Mapper.CreateMap<FileNameVariable, FileNameVariableViewModel>();
Mapper.CreateMap<EmailSetup, EmailSetupViewModel>();
Mapper.CreateMap<SelectedSection, SelectedSectionViewModel>();
Mapper.CreateMap<AvailableSection, AvailableSectionViewModel>();
Mapper.CreateMap<AvailableColumn, AvailableColumnViewModel>();
Mapper.CreateMap<Policy, PolicyViewModel>();
Mapper.CreateMap<SelectedColumn, SelectedColumnViewModel>();
Mapper.CreateMap<SelectedEmployeeSeaServiceType, SelectedEmployeeSeaServiceTypeViewModel>();
Mapper.CreateMap<SelectedEmployeeStatus, SelectedEmployeeStatusViewModel>();
Mapper.CreateMap<EmployeeStatus, EmployeeStatusViewModel>();
Mapper.CreateMap<EmployeeSubStatus, EmployeeSubStatusViewModel>();
Mapper.CreateMap<SelectedEmployeeSubStatus, SelectedEmployeeSubStatusViewModel>();
Mapper.CreateMap<SelectedSeaServiceType, SelectedSeaServiceTypeViewModel>();
GlobalExport globalExport = _service.GetGlobalExportById(1);
GlobalExportViewModel globalExportViewModel = Mapper.Map<GlobalExport, GlobalExportViewModel>(globalExport);
//Map ViewModel to Model
Mapper.CreateMap<GlobalExportViewModel, GlobalExport>();
Mapper.CreateMap<FileNameSetupViewModel, FileNameSetup>();
Mapper.CreateMap<FileNameVariableViewModel, FileNameVariable>();
Mapper.CreateMap<EmailSetupViewModel, EmailSetup>();
Mapper.CreateMap<SelectedSectionViewModel, SelectedSection>();
Mapper.CreateMap<AvailableSectionViewModel, AvailableSection>();
Mapper.CreateMap<AvailableColumnViewModel, AvailableColumn>();
Mapper.CreateMap<PolicyViewModel, Policy>();
Mapper.CreateMap<SelectedColumnViewModel, SelectedColumn>();
Mapper.CreateMap<SelectedEmployeeSeaServiceTypeViewModel, SelectedEmployeeSeaServiceType>();
Mapper.CreateMap<SelectedEmployeeStatusViewModel, SelectedEmployeeStatus>();
Mapper.CreateMap<EmployeeStatusViewModel, EmployeeStatus>();
Mapper.CreateMap<EmployeeSubStatusViewModel, EmployeeSubStatus>();
Mapper.CreateMap<SelectedEmployeeSubStatusViewModel, SelectedEmployeeSubStatus>();
Mapper.CreateMap<SelectedSeaServiceTypeViewModel, SelectedSeaServiceType>();
GlobalExport newGlobalExport = Mapper.Map<GlobalExportViewModel, GlobalExport>(globalExportViewModel);
_service.UpdateGlobalExport(newGlobalExport);
}
我收到此错误:
有人可以给出一些意见或更好的解决方案:P非常感谢你!
答案 0 :(得分:0)
此处的问题是GlobalExportRepository.UpdateGlobalExport
方法正在尝试将GlobalExport
对象附加到检索它的同一DbContext实例。
尝试修改GlobalExportRepository.UpdateGlobalExport
方法,将实体明确标记为已修改,只需调用DbContext.SaveChanges方法。
以下是一个例子:
public void UpdateGlobalExport(GlobalExport instance)
{
var entity = context.Entry(instance);
entity.State = EntityState.Modified;
context.SaveChanges();
}
对GlobalExport
实例will automatically be detected even if its state is Detached进行的任何更改。