Sequence contains no elements?
I'm currently using a single query in two places to get a row from a database.
BlogPost post = (from p in dc.BlogPosts
where p.BlogPostID == ID
select p).Single();
The query is fine when retrieving the row to put data in to the text boxes, but it returns an error "Sequence contains no elements" when used to retrieve the row in order to edit it and put it back in to the database. I can't understand why it might find an appropriate row in one instance but not another.
(Using ASP.NET MVC and LINQ)
Solution 1:
From "Fixing LINQ Error: Sequence contains no elements":
When you get the LINQ error "Sequence contains no elements", this is usually because you are using the
First()
orSingle()
command rather thanFirstOrDefault()
andSingleOrDefault()
.
This can also be caused by the following commands:
FirstAsync()
SingleAsync()
Last()
LastAsync()
Max()
Min()
Average()
Aggregate()
Solution 2:
Please use
.FirstOrDefault()
because if in the first row of the result there is no info this instruction goes to the default info.