Home > Net >  ERROR: InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'S
ERROR: InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'S

Time:10-12

I am trying to work on this but can't fix it. Can anyone help thanks!

I keep getting the error below when I try to run it. I am using mySQL database.

I get the line 31 highlighted.

enter image description here

namespace MyApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CustomerController : ControllerBase
    {
        private readonly MyApiDBContext _context;

        public CustomerController(MyApiDBContext context)
        {
            _context = context;
        }

        // GET: api/Customer
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Customer>>> GetCustomers()
        {
            if (_context.Customers == null)
            {
                return NotFound();
            }
            return await _context.Customers.ToListAsync();
        }

        // GET: api/Customer/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Customer>> GetCustomer(int id)
        {
            if (_context.Customers == null)
            {
                return NotFound();
            }
            var customer = await _context.Customers.FindAsync(id);

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

            return customer;
        }

CodePudding user response:

In your POCO class Customer, you should have a property of type string. This exception has been raised because the value of that property in DB is null and it can not be cast into string. You may fix it by changing the type of the property to Nullable< string> or string? .

  • Related