0

I am trying to get an object from the database and return to React in my c# controller. If I return the object as it comes from the database all works fine, but if I convert to a DTO object I get Object reference not set to an instance of an object error.

In my controller I have,

[HttpGet("interaction/{id}")]
        public async Task<ActionResult<DrugInteractionDTO>> getInteractionDetails(int id)
        {
            var interaction = await _context.DrugInteractions.FindAsync(id);

            if(interaction == null) {
                return NotFound();
            }

            return new DrugInteractionDTO
            {
                Severity = interaction.Severity,
                SeverityAsString = interaction.Severity.ToString(),
                ProDetailedInformation = interaction.ProDetailedInformation,
                BasicDetailedInformation = interaction.BasicDetailedInformation,
                Antifungal = interaction.AntifungalAgent.Name,
                InteractingDrug = interaction.InteractingDrug.GenericName,
                ID = interaction.ID
            };
        }

I have used this pattern many times to convert to a DTO before sending back to React without issue. I am not sure why I am getting an issue here.

My DrugInteractionDTO looks like this,

public class DrugInteractionDTO
    {
        public string Antifungal { get; set; }
        public string InteractingDrug { get; set; }
        public string BasicDetailedInformation { get; set; }
        public string ProDetailedInformation { get; set; }
        public Severity Severity { get; set; }
        public string SeverityAsString {get; set; }
        public int ID { get; set; }
    }
Danny Jebb
  • 802
  • 1
  • 7
  • 16
  • 1
    Verify that none of the fields you are using to create your DTO are null coming out of the DB. – Steve V Oct 31 '22 at 14:39
  • 1
    It seems likely that at least one of the properties being de-referenced on `interaction` is `null`. – David Oct 31 '22 at 14:39
  • You can check for null values in `debug` mode; One candidate for this error is the line `interaction.Severity.ToString()`, so you can use `interaction.Severity?.ToString()` – TheMah Oct 31 '22 at 15:52

0 Answers0