2

I am getting maximum code from database but how should I handle it when there is no record? It returns error as null reference no record

int maxCode = context.Persons.Max(p => p.pCode);

EDIT:

This answer is to check first time the null value when you deployed app other wise the suggested answer only match condition with id but i no want to match condition i only have to check weather there are records in table or not

Nouman Arshad
  • 63
  • 1
  • 9

1 Answers1

3

If there are no rows, maxCode is set to zero.

int maxCode = context.Persons.Any() ? context.Persons.Max(p => p.pCode) : 0;
jvanrhyn
  • 2,804
  • 19
  • 14