[RESOLVED]get rows count from database

how can I get the count of records in the table users in the applicationContextcreatedin the mvc project?

this is what I have tried so far:

var context = new ApplicationDbContext();
var count = context.Users
.Where(o => Convert.ToInt32(o.Id) == 1)
.Count();

if (count < 3)
{

//do whatever

}

it’s giving an error at the convert.ToInt32, and if I remove the convert it will give an error cannot implicity convert type ‘string’ to ‘int’ (o.Id) == 1)

what is going wrong?

If you want a count of the users within your specific Users table, you should be able to simply use :

using(var context = new ApplicationDbContext())
{
      // Get your count
      var count = context.Users.Count();

      // Additional logic omitted for brevity
}

Could you be a bit more specific about exactly what you are trying to do with your Id property and why you are trying to cast it? Based on your error message, your Id property is a string and unless it is an integer (as a string), converting it to an integer
will not work.

Hi

var count = context.Users.Count();

The above should work, am I missing something obvious here?

var context = new ApplicationDbContext();
var count = context.Users.Count(); // you will get the total users in the table

if (count < 3)
{

//do whatever

}

As o.Id is a string, then the easiest way it’s to use o.id == "1"

Leave a Reply