【发布时间】:2021-02-24 01:31:05
【问题描述】:
我有这门课下课。 student, studentrequest(Dto) , mapping profile 和 apicontroller。
我不知道为什么它映射到空值。
public class Student : BaseEntity, IAuditableEntity, IDeletableEntity
{
[Required]
public string StudentId { get; set; }
[Required]
public string NameKH { get; set; }
[Required]
public string NameEN { get; set; }
public string PhoneNumber { get; set; }
public string MotherNameKH { get; set; }
public string MotherNameEN { get; set; }
public string FatherNameKH { get; set; }
public string FatherNameEN { get; set; }
public string MotherPhoneNumber { get; set; }
public string FatherPhoneNumber { get; set; }
[Required]
public string CurrentAddress { get; set; }
[Required]
public string Nationality { get; set; }
[Required]
public string Ethnicity { get; set; }
[Required]
public DateTime DateOfBirth { get; set; }
[Required]
public string PlaceOfBirth { get; set; }
public string Notes { get; set; }
[Required]
public string CreatedBy { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public string LastModifiedBy { get; set; }
public DateTime? LastModifiedOn { get; set; }
public bool IsDeleted { get; set; }
public DateTime? DeletedOn { get; set; }
}
和 DTO
public class StudentRequest
{
[Required]
public string StudentId { get; set; }
[Required]
public string NameKH { get; set; }
[Required]
public string NameEN { get; set; }
public string PhoneNumber { get; set; }
public string MotherNameKH { get; set; }
public string MotherNameEN { get; set; }
public string FatherNameKH { get; set; }
public string FatherNameEN { get; set; }
public string MotherPhoneNumber { get; set; }
public string FatherPhoneNumber { get; set; }
[Required]
public string CurrentAddress { get; set; }
[Required]
public string Nationality { get; set; }
[Required]
public string Ethnicity { get; set; }
[Required]
public DateTime DateOfBirth { get; set; }
[Required]
public string PlaceOfBirth { get; set; }
public string Notes { get; set; }
}
映射配置文件
CreateMap<StudentRequest, Student>()
我的更新 API 控制器
[HttpPut("{id}")]
public async Task<ActionResult> Update(int id, StudentRequest studentRequest)
{
var student = await _context.Students.SingleOrDefaultAsync(x => x.IsDeleted != true && x.Id == id);
if (student == null) return NotFound(new ApiResponse(404, "Student Not Found"));
student = _mapper.Map<StudentRequest, Student>(studentRequest);
student.LastModifiedBy = GetCurrentUserName();
student.LastModifiedOn = DateTime.Now;
try
{
_context.Students.Add(student);
await _context.SaveChangesAsync(GetCurrentUserName(), GenerateIPAddress());
return Ok(new ApiResponse(200, "Succesfully Added Student"));
}
catch (Exception ex)
{
Log.Error(ex.Message);
return BadRequest(new ApiResponse(400, "Error Adding Student"));
}
}
这条线student = _mapper.Map<StudentRequest, Student>(studentRequest);
第一个学生已有CreatedBy、CreatedOn、数据。
但映射后,student.CreatedBy = null;
我不知道这个行为映射有什么问题。
【问题讨论】:
-
我不想在 createdby、createdon 上映射任何东西。但为什么它将现有值映射到 null
标签: asp.net automapper webapi