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

2
  • 1
    Possible duplicate of Max return value if empty query Commented Jan 17, 2016 at 16:31
  • 1
    Use DefaultIfEmpty - there are plenty of duplicates of this question. Commented Jan 17, 2016 at 16:32

1 Answer 1

3

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

int maxCode = context.Persons.Any() ? context.Persons.Max(p => p.pCode) : 0;
Sign up to request clarification or add additional context in comments.

2 Comments

context.Entry(p).GetDatabaseValues(); but why this is not allowing me to insert in database for first time when database have no value
GetDatabaseValues cannot be used for entities in the Added state.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.