How to make a LINQ query that returns the amount of people who were born per month?

Asked

Viewed 45 times

1

I would like to make a LINQ query that returns the amount of people who were born in the month.

In Mysql I do this query:

SELECT COUNT(*) AS DataNacimento FROM pessoas WHERE MONTH (DataNascimento) = '12';

At LINQ I tried to make this query, but does not accept:

var dataNascimento = db.Pessoas.Where(w => w.DataNascimento == "12").Count();

1 answer

1


It’s simpler than this, but you need to take the month, not translated correctly:

var qtdeNascidosDezembro = db.Pessoas.Count(w => w.DataNascimento.Value.Month == 12);

I put in the Github for future reference.

I put the Value because the column is as voidable (need it?) and there the access is indirect. If it really can have nulls the ideal would be to treat it and decide what to do when it comes null, otherwise it will give error. If no error should probably not allow null because none is. Could decide using the HasValaue or take the amount with the GetValueOrDefault().

  • Here for me instead of Month, only these options appear: Equals, Gethashcode, Gettype, Getvalueordefault, Hasvalue, Tostring and Value.

  • 1

    So there’s something wrong with your model, the problem is not with LINQ, you’re getting one Nullable and not a DateTime as expected. Try to see if you have Value.

  • That’s right, it was in "Summer Month".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.