You don’t specify the line number, but I would guess model.Age is a string.
System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32'.
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; }
}
}
2 answers
Sort by: Most helpful
-
-
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.