我正在使用automapper 9.0和.net core 2.2。 我想动态更新嵌套的类数据。
模型
public class Employee
{
public Guid Id {get;set;}
public bool IsDeleted {get;set;}
public string Name {get;set;}
public ICollection<EmployeeTitle> Titles {get;set;}
}
public class Title
{
public Guid Id {get;set;}
public bool IsDeleted {get;set;}
public string Name {get;set;}
public ICollection<EmployeeTitle> Employees {get;set;}
}
public class EmployeeTitle
{
public Guid Id {get;set;}
public bool IsDeleted {get;set;}
public Guid EmployeeId {get;set;}
public Employee Employee {get;set;}
public Guid TitleId {get;set;}
public Title Title {get;set;}
}
DTO
public class EmployeeTitleDto
{
public Guid Id {get;set;}
public bool IsDeleted {get;set;}
public Guid TitleId {get;set;}
}
public class EmployeeDto
{
public Guid Id {get;set;}
public string Name {get;set;}
public IList<EmployeeTitleDto> Titles {get;set;}
}
映射个人资料
CreateMap<EmployeeTitleDto, EmployeeTitle>();
CreateMap<EmployeeDto, Employee>();
这样,我可以在创建新员工记录时将标题添加为列表。 但是,当我想更新添加的标题时,我认为映射器将传入的记录粉碎为新记录。 ID重复错误。是否可以通过映射中的配置解决此问题?
更新请求(仅更新我想要的标题记录)
{
"id": "03A37A7A-EE23-49D2-B35F-6B532BA54953"
"name": "Emp Up",
"Titles": [
{
"TitleId": "04AB0651-D0F4-4B8F-9CE0-2DDFDB35ED35",
"isDeleted": true,
"id": "17561161-0861-4254-A12B-08D73C2E51BF"
},
{
"TitleId": "5F98137D-E05D-4927-9D66-875E1BF3584E",
"isDeleted": false,
"id": "6C054764-9CC7-4D4F-A12C-08D73C2E51BF"
}
],
}
更新服务
public async Task<bool> Update(EmployeeDto model)
{
var entity = await _context
.Employee
.Where(x=> x.Id == model.Id)
.Include(i => i.Titles)
.FirstOrDefaultAsync();
// I think the nested class here has been crushed. ??
_mapper.Map(model, entity);
await _uow.SaveChangesAsync();
return true;
}
这样做时,我尽量不指定应更新模型中的记录。 ID重复错误。如果映射器配置文件部分中有一个ID,我可以像更新吗?
错误
无法跟踪,因为已经跟踪了另一个具有相同'{'Id'}键值的实例。
但是我想更新!还是不要添加。