【问题标题】:How to fetch max number from the database in ASP.NET Core 6 API or replace the DTO field using Entity Framework Core?如何从 ASP.NET Core 6 API 中的数据库中获取最大数量或使用 Entity Framework Core 替换 DTO 字段?
【发布时间】:2022-01-17 04:42:04
【问题描述】:

我的要求是从数据库中获取最大数量并添加 +1 以使其不同。我可以使用自增ID,但根据要求不同

try
{
    logger.LogInformation($"Patient registered successfully");

    var patient = mapper.Map<Patient>(patientCreateDTO);
        
    await _context.Patient.AddAsync(patient);
    await _context.SaveChangesAsync();

    return CreatedAtAction("GetPatient", new { id = patient.Id }, patient);
}
catch (Exception e)
{
    logger.LogError(e, $" Error performing post in {nameof(PostPatient)}");
    return StatusCode(500, Messages.Error500Message);
}

【问题讨论】:

    标签: .net-core asp.net-core-webapi asp.net-core-6.0 ef-core-6.0


    【解决方案1】:

    我解决了在 asp.net core 6 中从数据库中获取最大数量的问题。将任何 DTO 字段从 NULL 替换为控制器端的默认值,而无需请求正文

      try
            {
                logger.LogInformation($"Patient Registred Successfully");
                
                var maxNumber= await _context.Patient.MaxAsync(e => e.Uhid);
                maxNumber+= 1;
              
                var patient = mapper.Map<Patient>(patientCreateDTO);
    
                if(maxNumber== null)
                {
                    maxNumber= 1;
                }   
              
                patient.Uhid = maxNumber;
             
                await _context.Patient.AddAsync(patient);
    
                await _context.SaveChangesAsync();
    
                return CreatedAtAction("GetPatient", new { id = patient.Id }, patient);
            }
    
            catch (Exception e)
            {
                logger.LogError(e, $" Error Performing Post in {nameof(PostPatient)}");
                return StatusCode(500, Messages.Error500Message);
              
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-19
      相关资源
      最近更新 更多