Wednesday, 15 August 2012

c# - False "Sequence contains no elements" exception when using Single() -



c# - False "Sequence contains no elements" exception when using Single() -

i seem having issue false exception thrown when using .single() in linq statement. checking debugger found list contain element looking , id field matches. code throws exception

public actionresult details(int id = 0) { filterqueue filterqueue = db.filterqueues.single(f => f.filterqueueid == id); if (filterqueue == null) { homecoming httpnotfound(); } homecoming view(filterqueue); }

however, switching more verbose coding style works. this:

public actionresult details(int id = 0) { filterqueue filterqueue = null; foreach (var f in db.filterqueues) { if (f.filterqueueid == id) filterqueue = f; } if (filterqueue == null) { homecoming httpnotfound(); } homecoming view(filterqueue); }

funnily enough, if allow code run past exception, grab right item display details of.

now, of course, can switch single singleordefault , works fine; however, since first code block written automatically framework, want understand doing wrong. if making systematic mistake, right right way.

i think looking singleordefault().

in code, checking null, when null never result of single();

here's want:

public actionresult details(int id = 0) { filterqueue filterqueue = db.filterqueues.singleordefault(f => f.filterqueueid == id); if (filterqueue == null) { homecoming httpnotfound(); } homecoming view(filterqueue); }

c# linq asp.net-mvc-4

No comments:

Post a Comment