Warm tip: This article is reproduced from stackoverflow.com, please click
asp.net asp.net-core asp.net-mvc-4

InvalidOperationException: Sequence contains no elements. In Asp.net Core MVC with Entity framework

发布于 2020-04-11 11:37:59

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

Questioner
SK jha
Viewed
18
SK jha 2020-02-14 18:58

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();
    }