System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32'.

Muhamamd Hammad Tahir 0 Reputation points
2024-07-28T08:01:00.3233333+00:00

public async Task UpdateEmployeeAsync(int id, Employee model)

{

  var employeee = await _appDbContext.Employees.FindAsync(id);

  if (employeee == null)

  {

      throw new Exception("Employee not found");

  }

  employeee.Name = model.Name;

  employeee.Phone = model.Phone;

  employeee.Age = model.Age;

 

  await _appDbContext.SaveChangesAsync();

}

namespace emp_curd.Data

{

public class Employee

{

    public int Id { get; set; }

    public string Name { get; set; }

    public string Email { get; set; }

    public string Phone { get; set; }

    public int Age { get; set; }

    //public object salery { get;  set; }

}

}

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,554 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 65,211 Reputation points
    2024-07-28T18:28:39.0133333+00:00

    You don’t specify the line number, but I would guess model.Age is a string.

    0 comments No comments

  2. Brando Zhang-MSFT 3,686 Reputation points Microsoft Vendor
    2024-07-29T07:18:52.22+00:00

    Hi @hammad tahir,

    According to the error message , it facing the error when saving the new employee. The reason why you face this error is you pass the wrong type's model.Age to the Age.

    I suggest you could recheck the model to make sure it is the right int type.

    More details, you could refer to below codes:

      
            var employee = await _appDbContext.Employees.FindAsync(id);
            if (employee == null)
            {
                throw new Exception("Employee not found");
            }
            // Validate and parse Age
            if (!int.TryParse(model.Age, out int parsedAge))
            {
                throw new InvalidCastException("Age is not a valid integer");
            }
            employee.Name = model.Name;
            employee.Phone = model.Phone;
            employee.Age = parsedAge;
            await _appDbContext.SaveChangesAsync();
        
       
    

    This will directly throw the error if the Age is not a valid int type value.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

     

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.