Exception of type 'System.InvalidOperationException' occurred in System.Core.dll but was not handled in user code

asp.net c# entity-framework exception list

Accepted Answer

This sentence:

var kategoria = db.Kategorie
                  .Include("Kursy")
                  .Where(k => k.NazwaKategorii.ToUpper() == nazwaKategori.ToUpper())
                  .Single();

You just called.Single() This implies you're guaranteeing that the result will always include precisely one record. The error informs you that the result returned zero records, therefore the call to.Single() fails.

Since it's possible for the result to include no records, use this alternative:.SingleOrDefault() then look at the outcome fornull . Possibly like this:

var kategoria = db.Kategorie
                  .Include("Kursy")
                  .Where(k => k.NazwaKategorii.ToUpper() == nazwaKategori.ToUpper())
                  .SingleOrDefault();
if (kategoria == null)
{
    // no record was found.
    // handle that situation in whatever way makes sense for your system.
}

You must also check for the possibility of multiple records returning as both scenarios are plausible..Single() and .SingleOrDefault() throws an error if there are several results (as their names imply, really). Items like.FirstOrDefault() or supplementary.Where() In such situation, clauses, etc., may be useful to locate the desired record.

4
1/28/2017 1:15:01 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow