How to fix this issue? When I run my code, from my home page, then when I go to suppliers page, the following error shows up:
InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32'.
Microsoft.Data.SqlClient.SqlBuffer.get_Int32()
Microsoft.Data.SqlClient.SqlDataReader.GetInt32(int i)
lambda_method37(Closure , QueryContext , DbDataReader , ResultContext , SingleQueryResultCoordinator )
Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable+AsyncEnumerator.MoveNextAsync()
System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable+ConfiguredValueTaskAwaiter.GetResult()
Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync(IQueryable source, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync(IQueryable source, CancellationToken cancellationToken)
Liquidation.Controllers.SuppliersController.Index() in SuppliersController.cs
- var suppliers = await _context.Suppliers.OrderBy(s => s.SeqNo).ToListAsync();
This is the code:
public async Task<IActionResult> Index()
{
var suppliers = await _context.Suppliers.OrderBy(s => s.SeqNo).ToListAsync();
return View(suppliers);
}
And this is in my model class:
[Display(Name = "Seq No")]
public int SeqNo { get; set; }
SeqNois stored as a string in your database. In other words, retrievedSuppliersrecords haveSeqNoas string data type. However, your view model expectsSeqNos to be integers and tries to cast them but it doesn't know how to do it. How to fix it? Well, it depends on what the actual problem is. Is the problem view model not knowing how to cast it? If that's the case, use something likeInt.Parse()orInt32.TryParse(). Or is the problem the data type ofSeqNoin your view model? If that's the case, then you don't need a cast at all. Just makeSeqNoastring.