请问我正在开发一个Asp.Net core项目,目标是.Net 5,具有干净的架构。
我在核心层
中有这个实体
考试实体:
public class Exam : IExam
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public DateTime ExamDate { get; set; }
[Required]
public TimeSpan ExamTime { get; set; }
[Required]
public decimal DurationByHour { get; set; }
[Required]
public string GroupId { get; set; }
[Required]
public string SchoolSubjectId { get; set; }
[Required]
public string ProfId { get; set; }
public virtual Group Group { get; set; }
public virtual SchoolSubject SchoolSubject { get; set; }
public virtual Prof Prof { get; set; }
public virtual ICollection<ExamMark> ExamMarks { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public bool IsEdited { get; set; }
public string LastEditor { get; set; }
public DateTime LastEditDate { get; set; }
}
我有这个 View 模型(用于编辑)一个 Exam
对象
ExamEditVm 查看模型/DTO:
public class ExamEditVm
{
public int Id { get; set; }
public DateTime ExamDate { get; set; }
public TimeSpan ExamTime { get; set; }
public decimal DurationByHour { get; set; }
public string GroupId { get; set; }
public List<Group> Groups { get; set; }
}
很好,现在当用户在编辑 View 中进行一些编辑并提交结果时,中的另一个编辑
操作结果 HTTPPOST 将以 ExamEditVm
对象的形式接收编辑。
此时,该操作应选择应编辑的考试,并使用MappingProfile
该操作将ExamEditVm
对象映射到选定的考试
对象
Exam
和 ExamEditVm
之间的映射配置文件:
CreateMap<Exam , ExamEditVm>().ReverseMap();
HttpPost 编辑操作结果:
public async Task<IActionResult> Edit(ExamEditVm model)
{
if (ModelState.IsValid)
{
var exam = await _examRepository.GetByIdAsync( model.Id );
exam = _mapper.Map<Exam>( model);
exam.WriteEditingAudit( _appUser );
await _examRepository.UpdateAsync( record : exam );
await _uow.CommitAsync();
return RedirectToAction( nameof( Edit ) , new {model.Id} );
}
// Some logic
}
到底是什么问题? 问题出在这一行
exam = _mapper.Map<Exam>( model);
当从 ExamEditVm
映射到 Exam
时,exam
将丢失所有未映射的属性值,因为他获得了另一个对象值。
那么,如何从 ExamEditVm
映射到 Exam
并在使用 Automapper
映射后保留 exam
对象旧的未映射属性值> 和 MappingProfile
?
希望您能理解这个问题。 所以请为他的问题提供任何解决方案。
最佳答案
通过执行 exam = _mapper.Map<Exam>(model);
您实际上正在创建一个新的 Exam
实例,
仅包含 ExamEditVm model
中的数据.
您想要做的是应用/映射 ExamEditVm model
中的数据反对现有Exam exam
对象。
为此,您必须使用 Map
传递源对象和目标对象的重载:
_mapper.Map(model, exam);
关于c# - 使用 Automapper 将某些属性从 TSource 映射到 TDestination,而不会丢失旧的其他 TDestination 对象属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68894925/