1

I am getting this error one of my projects.

InvalidOperationException: Sequence contains no elements.

here is my code in this I am trying to create auto-generated Id with string format.

 public async Task<IActionResult> Create()
    {
        int id = _db.Patient.Max(item => item.Id)+1;

        ViewBag.autoid = "BL0000"+id.ToString(); 
        return View();
    }

enter image description here

0

3 Answers 3

1

The max method will throw the InvalidOperation exception if the sequence contains no elements. - https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.max?view=netframework-4.8

You could use some extension methods like this - https://stackoverflow.com/a/18100382/38024

public static T MaxOrEmpty<T>(this IQueryable<T> query)
{
    return query.DefaultIfEmpty().Max();
}
Sign up to request clarification or add additional context in comments.

Comments

1

I resolved this issue

public async Task<IActionResult> Create()
    {
        //x = _db.Patient.Max(item => item.Id);
        x=_db.Patient.DefaultIfEmpty().Max(item => item == null ? 1 : item.Id+1);


        ViewBag.autoid = "BL0000"+x.ToString(); 
        return View();
    }

Comments

0

InvalidOperationException: Sequence contains no elements.

As the error message said,you do not have such elements in your Patient.So you need to judge whether it contains item or not.

Try this:

var data = _db.Patient.Select(item => item.Id);
if(data.Count()==0)
{
    int id = 1; 
}
else
{
    int id = data.Max() + 1;
}

Comments

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.