I have this simple query where I want to return a column of a record from a table which can be either 1 or 0. I am trying to use this query but I get a conversion error:
System.InvalidCastException: 'Unable to cast object of type 'System.Boolean' to type 'System.Int32'.'
public int GetUserValidFlag(int userId)
{
var query = from r in db.VisUsers
where r.UserId == userId
select r.IsValid;
return Convert.ToInt32(query.FirstOrDefault());
}
I do have an instance of db in this class.
Context:
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
}
public DbSet<Category> Categories { get; set; }
public DbSet<SubCategory> SubCategories { get; set; }
public DbSet<VisUser> VisUsers { get; set; }
public DbSet<Project> Projects { get; set; }
}
I have also tried with Find():
public int GetUserValidFlag(int userId)
{
var record = db.VisUsers.Find(userId);
return Convert.ToInt32(record.IsValid);
}
NOTE: these two attempts do not reach the return statements, the error occurs before the return.
I am unsure where/why this conversion error is occurring, I can make it work with stored procedure but I would like to understand why this version is failing.
VisUsermodel please. Is this EF code first?r.IsValidis null for the particular user you're selecting, or 2)userIddoesn't exist indb.VisUsers, sor.IsValidis null. Also, if it's a boolean flag why isn't the method signaturepublic bool GetUserValidFlag(int userId)?Convert.ToInt32sure looks like a conversion to Int32 to me... why don't you start there?