Ad

Unable To Cast Object Of Type 'System.String' To Type 'System.Int32' While Using ToListAsync()

- 1 answer

While loading values of a database to a list (using ToListAsync()) I get this error

This is the model I'm using:

[Key]
public int id { get; set; }
public String password { get; set; }

this is the code behind (.cshtml.cs) code:

private readonly ApplicationDbContext _db;
public PassStrengthModel(ApplicationDbContext db)
{
    _db = db;
}
public IList<toptenthousand> toptenthousand { get; set; }
public async Task OnGetAsync()
{
    toptenthousand = await _db.toptenthousand.ToListAsync();
}

Database I'm working with screenshot of dbscreenshot of datatypes | github link (I've added an id column which is not present in the repo)

I can't understand the problem here,
is it problem with db having both string and int values and me keeping the "password" var as string in the Model,
or I'm using ToListAsync() in a wrong way?

Ad

Answer

I think the "Id" column in the database is nvarchar type or some sort of text type. The function ToListAsync() tries to convert a string to an int, and the only int in the model is the id. So I guess the id in the database is string type.

Ad
source: stackoverflow.com
Ad