Home > Mobile >  ASP.NET Core API - How to insert extra fields into the DB after mapping
ASP.NET Core API - How to insert extra fields into the DB after mapping

Time:12-15

In my ASP.NET Core Web API, I have this model:

Job:

public class Job
{
    [Key]
    public long Id { get; set; }
    public string JobTitle { get; set; }
    public string JobStatus { get; set; }
    public long UserId { get; set; }
    public string JobDescription { get; set; }
}

DTO:

public class JobCreationRequestDto
{
    public string JobTitle { get; set; }
    public string JobDescription { get; set; }
}

public class JobResponseDto
{
    public long Id { get; set; }
    public string JobTitle { get; set; }
    public string JobDescription { get; set; }
}

One User can place several jobs

Mapping:

public class JobMapProfile : Profile
{
    public JobMapProfile()
    {
        CreateMap<JobCreationRequestDto, Job>();
        CreateMap<Job, JobResponseDto>();
    }
}

Service:

public interface IJobService
{
    Task<GenericResponseDto<JobResponseDto>> CreateJobAsync(JobCreationRequestDto requestDto);
}

    public async Task<GenericResponseDto<JobResponseDto>> CreateJobAsync(JobCreationRequestDto requestDto)
    {
        var response = new GenericResponseDto<JobResponseDto>();
        var userId = _userResolverService.GetUserId();
        var jobStatus = "Processed";

            try
            {
                var job = _mapper.Map<Job>(requestDto);
                _context.Jobs.Add(job);
                await _context.SaveChangesAsync();

                response.StatusCode = 201;
                response.Result = _mapper.Map<JobResponseDto>(job);
            }
            catch (Exception ex)
            {
                response.Error = new ErrorResponseDto()
                {
                    ErrorCode = 500,
                    Message = ex.Message
                };
            }
        } 
        return response;
    }

Controller:

    [HttpPost, Route("")]
    public async Task<ActionResult<GenericResponseDto<JobResponseDto>>> CreateJob(JobCreationRequestDto request)
    {
        var response = await _service.CreateJobAsync(request);
        Response.StatusCode = response.StatusCode ?? StatusCodes.Status201Created;
        return new JsonResult(response);
    }

In the service, before await _context.SaveChangesAsync() is implemented, I want to include this:

JobStatus = jobStatus;

UserId = userId;

How do I achieve this?

Thanks

CodePudding user response:

After mapping the requestDto model to the Job model, you could set the JobStatus or userid for the job object, code like this:

var job = _mapper.Map<Job>(requestDto);  
job.JobStatus = jobStatus;  
//job.UserId = userId;
_context.Jobs.Add(job);
  • Related