Ah Kim
Ah Kim

Reputation: 33

How to count the number of records in the model with ASP.NET MVC?

I want to count the number of records contained in the Suspenses property with a year of "2013" and a month of "1".

I get the error when I run the below code: "DbComparisonExpression requires arguments with comparable types." I'm still new to ASP.Net MVC, not sure if this is the way to get my results. Hopefully I can learn from your comments. Your help will be appreciated.

 var suspenses = db.Suspenses.Include(s => s.User);
 int[] count = new int[12];

 for (var i = 1; i <= 12; i++)
 {
     // to count number of account suspenses on every months
     suspenses = suspenses.Where(s => s.SuspenseDate.Year.Equals(year));
     suspenses = suspenses.Where(s => s.SuspenseDate.Month.Equals(i));
     count[i-1] = suspenses.Count();
 }

Upvotes: 1

Views: 8753

Answers (3)

Jnavid D
Jnavid D

Reputation: 1

you can use sum in your order

var suspenses = db.Suspenses.sum(s => s.User).where(m => m.mounth == 12);

Upvotes: 0

mayabelle
mayabelle

Reputation: 10014

Try this:

int recordsInJanuary2013 = 
    db.Suspenses.Count(se => se.SuspenseDate.Month == 1 
                             && se.SuspenseDate.Year == 2013);

Upvotes: 1

Kristof
Kristof

Reputation: 3315

You can do it in a single line by grouping per month and counting the total like this :

var count = db.Suspenses.GroupBy(s => s.SuspenseDate.Month).Select(g=>g.Count());

Upvotes: 0

Related Questions