Unable to cast object of type 'System.Guid' to type 'System.String'

Edward Colmenarez 0 Reputation points

Im getting this error when i get a record from the database. On my colum in mysql i have the id as uuid() for default, lenght 36 char value. I created the models with entityframework reverse enginnering and in my model at first it was set as Guid, but then the error was that it can't cast from char(36) to a Guid. then i change id to string value and it returns the error Unable to cast object of type 'System.Guid' to type 'System.String', now i dont know what should i do.

At the second line is where i get the error.

var dbContext = _dbContextOptions;

Customer customer = dbContext.Customers.Where(c => c.No == customerJson.CUSTNMBR).FirstOrDefault();
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
632 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Vahid Ghafarpour 8,545 Reputation points

    The error message suggests that there is a type mismatch between the database column type and the type of the corresponding property in the Customer class.

    Since you have changed the id property in your Customer model to a string, you need to ensure that the corresponding column in the database is also of type varchar or char(36) to accommodate the UUID values.

    If the column is already of type varchar or char(36), then you may need to modify the code that retrieves the customer record. Try updating the LINQ query to cast the UUID value to a string before comparing it with the customer number:

    Customer customer = dbContext.Customers.FirstOrDefault(c => c.Id.ToString() == customerJson.CUSTNMBR);

    This should retrieve the customer record based on the string representation of the UUID value in the "Id" property.

    If the above solution does not work, then you may need to check your model class and database schema to ensure they are correctly configured to use UUID values for the Id property.

    0 comments No comments