-1

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; }
2
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Oct 15 at 1:56
  • 8
    It looks like SeqNo is stored as a string in your database. In other words, retrieved Suppliers records have SeqNo as string data type. However, your view model expects SeqNos 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 like Int.Parse() or Int32.TryParse(). Or is the problem the data type of SeqNo in your view model? If that's the case, then you don't need a cast at all. Just make SeqNo a string. Commented Oct 15 at 3:20

1 Answer 1

1

Try this

var suppliers = await _context.Suppliers
    .OrderBy(s => Convert.ToInt32(s.SeqNo))   // or int.Parse
    .ToListAsync();

But note: doing this may force client-side evaluation or prevent certain optimizations, so it’s not ideal for large sets.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.