0

I am fairly new to MVC and EF, and what I am trying to show the data from my database to my view. This is my action:

public ActionResult MalfunctionsList(MalfunctionDTO malfunctionDTO)
    {
        var malfunctions = _context.Malfunctions.ToList();
        var customer = _context.Malfunctions.Single(c => c.Id == malfunctionDTO.CustomerId);
        var movie = _context.Malfunctions.Where(m => malfunctionDTO.MovieIds.Contains(m.Id)).ToList();

        return View(malfunctions);
    }

When code runs I get System.InvalidOperationException: Sequence contains no elements in this line:

var customer = _context.Malfunctions.Single(c => c.Id == malfunctionDTO.CustomerId);

This is my DTO:

public class MalfunctionDTO
{
    public int CustomerId { get; set; }

    public List<int> MovieIds { get; set; }

    public Customer Customer { get; set; }

    public Movie Movie { get; set; }

    public string ReportDescription { get; set; }

}

In my table in the database the customerId isn't empty.

IlirAs
  • 17
  • 1
  • 7

2 Answers2

0

Seems like for some item in Malfunctions this query finds no elements

Malfunctions.Single(c => c.Id == malfunctionDTO.CustomerId);

try

.SingleOrDefault()
Curiousdev
  • 5,668
  • 3
  • 24
  • 38
0

Single(condition), is a linq extension method that return the one and only element that match the condition that passed into. If there is no element that match the condition or maybe multiple elements that do match , it throws error. In your case there is no elements that match this condition in your database. BTW, you can use singleOrDefault instead of throwing exception it return the default value , null. Or maybe Malfunctions contains nothing before the single method , so it can't iterates nothing.

  • SingleOrDefault() returns null value, why is it returning a null value if it does have a value in my table? – IlirAs Oct 06 '17 at 10:07
  • As I said , if you are certain that the condition is true , so please make sure that there is a single element (not more than 1), or else it will return null. Else you should debug the program and see whats the matter , is var malfunctions hold an empty list after the ToList()? – Shahar Sadkovich Oct 06 '17 at 10:12
  • There can be more than 1 item in the list with the same customerId in the database table. Debugger shows that var malfunctions isn't empty it holds the entire list of _context.Malfunctions – IlirAs Oct 06 '17 at 10:30
  • I see, look single/singleordefault return single element or exception/null if there non/more then one. If you want the first one , use First() else use Where() to get all matching elements – Shahar Sadkovich Oct 06 '17 at 10:34