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)
David Basarab
71.5k42 gold badges129 silver badges155 bronze badges
asked Aug 24, 2009 at 19:19
3
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()
V0d01ey
451 silver badge6 bronze badges
answered Dec 5, 2011 at 13:43
Tony KiernanTony Kiernan
4,9372 gold badges14 silver badges10 bronze badges
11
Please use
.FirstOrDefault()
because if in the first row of the result there is no info this instruction goes to the default info.
![]()
answered Jun 21, 2016 at 22:23
![]()
1
Well, what is ID here? In particular, is it a local variable? There are some scope / capture issues, which mean that it may be desirable to use a second variable copy, just for the query:
var id = ID;
BlogPost post = (from p in dc.BlogPosts
where p.BlogPostID == id
select p).Single();
Also; if this is LINQ-to-SQL, then in the current version you get a slightly better behaviour if you use the form:
var id = ID;
BlogPost post = dc.BlogPosts.Single(p => p.BlogPostID == id);
JoshJordan
12.6k10 gold badges52 silver badges63 bronze badges
answered Aug 24, 2009 at 19:23
![]()
Marc GravellMarc Gravell
1.0m259 gold badges2529 silver badges2876 bronze badges
1
In addition to everything else that has been said, you can call DefaultIfEmpty() before you call Single(). This will ensure that your sequence contains something and thereby averts the InvalidOperationException «Sequence contains no elements». For example:
BlogPost post = (from p in dc.BlogPosts
where p.BlogPostID == ID
select p).DefaultIfEmpty().Single();
![]()
Stephen Rauch♦
46.6k31 gold badges109 silver badges131 bronze badges
answered Sep 24, 2018 at 1:41
![]()
bryc3monk3ybryc3monk3y
4148 silver badges12 bronze badges
This will solve the problem,
var blogPosts = (from p in dc.BlogPosts
where p.BlogPostID == ID
select p);
if(blogPosts.Any())
{
var post = blogPosts.Single();
}
answered Jan 16, 2013 at 0:31
![]()
Diganta KumarDiganta Kumar
3,6173 gold badges26 silver badges29 bronze badges
2
I had a similar situation on a function that calculates the average.
Example:
ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Average();
Case Solved:
ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Count == 0 ? 0 : lstMediaValues.Average();
answered Apr 25, 2019 at 11:13
Reason for error:
-
The query
from p in dc.BlogPosts where p.BlogPostID == ID select preturns a sequence. -
Single()tries to retrieve an element from the sequence returned in step1. -
As per the exception — The sequence returned in step1 contains no elements.
-
Single() tries to retrieve an element from the sequence returned in step1 which contains no elements.
-
Since
Single()is not able to fetch a single element from the sequence returned in step1, it throws an error.
Fix:
Make sure the query (from p in dc.BlogPosts where p.BlogPostID == ID select p)
returns a sequence with at least one element.
![]()
Ali
3,2935 gold badges39 silver badges53 bronze badges
answered Feb 2, 2016 at 12:41
Siddarth KantedSiddarth Kanted
5,6481 gold badge29 silver badges20 bronze badges
- Remove From My Forums
-
Question
-
Hi NG,
I’m using the following statemtn to get a record from my database
Code Snippet
var productItem = productDtcx.Product.Single(p => p.ProductNumber == «TP00002»);
In case, when this record is not existing in my database I’m receiving the following exception:
Code Snippet
System.InvalidOperationException was unhandled
Message=»Sequence contains no elements»
Source=»System.Core»
StackTrace:
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at System.Data.Linq.SqlClient.SqlProvider.SqlQueryResults`1.PostProcess(Expression query, IEnumerable`1 results)
at System.Data.Linq.SqlClient.SqlProvider.SqlQueryResults`1.GetEnumerator()
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at System.Data.Linq.Table`1.System.Linq.IQueryable.Execute[S](Expression expression)
at System.Linq.Queryable.Single[TSource](IQueryable`1 source, Expression`1 predicate)
at Sample0040.Program.Main(String[] args) in C:Documents and SettingsoaytekinDesktopLINQSamplesSample0040Program.cs:line 19
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:I don’t want to catch this exception with a try/catch block. Is there any another method/way to check, if a record is existing or not?
I want to delete a record. To get and delete the record I’m using the following code
Code Snippet
string connString = «Data Source=.;Initial Catalog=AdventureWorks;Integrated Security=True»;
ProductDataContext productDtcx = new ProductDataContext(connString);
var productItem = productDtcx.Product.Single(p => p.ProductNumber == «TP00002»);
productDtcx.Product.Remove(productItem);
Thx for your help,
Ozgur Aytekin
Answers
-
Use SingleOrDefault. It returns null if the row isn’t found.
Anders
If you are using LINQ or Lambda expression and getting error: InvalidOperationException “Sequence contains no elements”. It means you are trying to retrieve an element from an empty sequence(may be returned by LINQ query). There are some basic rules to handle this in LINQ or lambda expression.
1. If you are using Single in LINQ, change your habit to use SingleOrDefault.
2. If you are using First or Last in LINQ, use FirstOrDefault or LastOrDefault.
3. If you are using ElementAt, use ElementAtOrDefault.
4. If you are getting this error on Aggregate Functions like Average, Sum…etc.
To understand this, let us take an example. See following code.
var items = new int[] {1, 2, 3, 4, 5};
Double avg = items.Average();
You will get avg = 3.0
Now, On adding where condition as in following, you will get error InvalidOperationException “Sequence contains no elements”.
Double avg = items.Where(x=>x > 10).Average();
because there is no item greater than 10. So what is the solution? Do you need to add one if condition every time to check whether items are available or not?
You need not to change code too much, Just use DefaultIfEmpty function before Aggregate Function.
Double avg = items.Where(x=>x > 10).DefaultIfEmpty().Average();
Now, avg = 0.0
Hope, It helps.
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (14ms) [Parameters=[@__userId_0='1'], CommandType='Text', CommandTimeout='30']
SELECT MAX([t].[Sequence])
FROM (
SELECT NULL AS [empty]
) AS [empty]
LEFT JOIN (
SELECT [a].[Id], [a].[Sequence], [a].[UserId]
FROM [Areas] AS [a]
WHERE [a].[UserId] = @__userId_0
) AS [t] ON 1 = 1
fail: Microsoft.EntityFrameworkCore.Query[10100]
An exception occurred while iterating over the results of a query for context type 'SomeDbContext'.
System.InvalidOperationException: Sequence contains no elements.
at lambda_method(Closure , QueryContext , DbDataReader , ResultContext , Int32[] , ResultCoordinator )
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
System.InvalidOperationException: Sequence contains no elements.
at lambda_method(Closure , QueryContext , DbDataReader , ResultContext , Int32[] , ResultCoordinator )
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
Unhandled exception. System.InvalidOperationException: Sequence contains no elements.
at lambda_method(Closure , QueryContext , DbDataReader , ResultContext , Int32[] , ResultCoordinator )
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.Max[TSource](IQueryable`1 source)
at Program.Main() in /home/ajcvickers/AllTogetherNow/Daily/Daily.cs:line 27
Problem
Error message when opening a template in Clarity:
«Clarity.10017 Template build process failed to complete.
Clarity.10023 Error populating grid for maps.
System.InvalidOperationException Sequence contains no elements»
Symptom
When a certain query returns no results (depending on selected page options), the MDX query will be incorrect and will produce the following error in Clarity:
«Clarity.10017 – template build process failed to complete
Clarity.10023 – error populating grid for maps
System.InvalidOperationExceptions – Sequence contains no elements.»
Cause
This is usually caused by one or multiple queries on the database that returns no members. This happens because the OLAP query does not return any rows for a certain combination and it looks like this is the expected behavior for Analysis Services. In other words, the query needs to have a member to search on, otherwise the above error will appear when running the report.
Diagnosing The Problem
Open the template in the Clarity interface
Observe the above error message
Resolving The Problem
Most likely, one of the intersection generated by the template does not exist in the database and one possible cause is that one or multiple members may no longer exist in the cube.
If this is the case, double check if the members added on the template in Studio still exist in the cube.
In order to do that open the template in Studio, under Data, verify the Row and Column members; try to re-select them from the Available Members container. You can locate a dimension member by using the Search box.
After replacing the non-existing members with the existing ones, the template should render as expected.
[{«Product»:{«code»:»SSMVH7″,»label»:»Clarity 7″},»Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Component»:»Clarity Server»,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»7.2;7.0″,»Edition»:»»,»Line of Business»:{«code»:»LOB10″,»label»:»Data and AI»}}]
Hello, I am using the below code to fetch some data from database and getting the error «Sequence contains no elements«
public static IEnumerable<CompanyLicenseKey> GetCompanyLicenseKey()
{
OPEntities onepassDB = new OPEntities();
//Let's get the onepass User model first
var user = onepassDB.UserAccounts.Where(x => x.Email == OnePassUserAccountEmail).First(); //error in this line
var userLicenseList = from c in user.CompanyProfiles
join l in onepassDB.CompanyLicenseKeys.Where(x => x.IsDisabled == false)
.Select(x => new { x.CRMID, x.LicenseKey, x.FriendlyName, x.ProductName })
on new { c.CRMID } equals new { l.CRMID }
select new Models.OnePass.CompanyLicenseKey { LicenseKey = l.LicenseKey, FriendlyName = l.FriendlyName, ProductName = l.ProductName };
if (ProductName == "")
return userLicenseList.ToList().OrderBy(x => x.FriendlyName);
else
return userLicenseList.Where(x => x.ProductName == ProductName).ToList().OrderBy(x => x.FriendlyName);
}
Error image

So how to solve this error? Or handle this error and get rid of it?
Asked by:- jon
1
: 5985
At:- 2/23/2018 8:42:37 AM
C#
entity-framework
asp.net-mvc
3 Answers
According to error, there is no element in the database of the same name and email id, please debug your code and also try to use .FirstOrDefault() instead of .First(), to avoid errors like this
You can try like this
var user = onepassDB.UserAccounts.Where(x => x.Email == OnePassUserAccountEmail).FirstOrDefault();
if(user != null)
{
//do something here
}
You can also use .SingleOrDefault() instead of .First(), it also returns null when no element is found.
This can also be caused by the following commands:
- FirstAsync()
- SingleAsync()
- Last()
- LastAsync()
- Max()
- Min()
- Average()
- Aggregate()
So similarly, try to use SingleOrDefaultAsync() instead of FirstAsync().
2
At:- 2/23/2018 3:56:32 PM
Updated at:- 11/23/2022 6:01:27 AM

Answered by:- jaya
There are some basic rules to handle this error in LINQ or lambda expression
- If you are using Single in LINQ, change your habit to use SingleOrDefault.
- If you are using First or Last in LINQ, use
FirstOrDefault or LastOrDefault. - If you are using ElementAt, use ElementAtOrDefault.
1
At:- 2/26/2018 6:55:30 AM
You can also use DefaultIfEmpty() before using Single() or
First(), to avoid error «sequence contains no elements» as it will ensure, there is an item in the sequence.
var user = onepassDB.UserAccounts.Where(x => x.Email == OnePassUserAccountEmail).DefaultIfEmpty().First();
Thanks.
0
At:- 12/15/2022 2:22:07 PM
When you start playing with LINQ queries over sequences of elements (e.g. getting min / max value for enumerable source) sooner or later you will come across this one — the InvalidOperationException (“Sequence contains no elements”).
The problem occurs as by default queries like IEnumerable<T>.Min(…) and IEnumerable<T>.Max(…) do not play nicely if you try to execute them on an empty sequence and just throw the exception described above. Unfortunately these methods do not have a corresponding counterpart like Single(…) / SingleOrDefault(…) that is smart enough to query the sequence if it is not empty or alternatively use the default value without raising an exception.
Basically you got two options now:
- Either perform the check on the enumerable sequence every time you are querying it
- OR integrate the logic in an extension method.
The second approach is much preferable so let’s add the missing link below:
namespace ExtensionMethods
{
using System;
using System.Collections.Generic;
using System.Linq; public static class IEnumerableExtensions
{
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the minimum Double value
/// if the sequence is not empty; otherwise returns the specified default value.
/// </summary>
/// <typeparam name=»TSource»>The type of the elements of source.</typeparam>
/// <param name=»source»>A sequence of values to determine the minimum value of.</param>
/// <param name=»selector»>A transform function to apply to each element.</param>
/// <param name=»defaultValue»>The default value.</param>
/// <returns>The minimum value in the sequence or default value if sequence is empty.</returns>
public static double MinOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector, double defaultValue)
{
if (source.Any<TSource>())
return source.Min<TSource>(selector); return defaultValue;
} /// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum Double value
/// if the sequence is not empty; otherwise returns the specified default value.
/// </summary>
/// <typeparam name=»TSource»>The type of the elements of source.</typeparam>
/// <param name=»source»>A sequence of values to determine the maximum value of.</param>
/// <param name=»selector»>A transform function to apply to each element.</param>
/// <param name=»defaultValue»>The default value.</param>
/// <returns>The maximum value in the sequence or default value if sequence is empty.</returns>
public static double MaxOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector, double defaultValue)
{
if (source.Any<TSource>())
return source.Max<TSource>(selector); return defaultValue;
}
}
}
Now you only need to add the using ExtensionMethods; directive in your project and you are all set:
Hope this helps.
Comments
All articles
Topics
Latest Stories
in Your Inbox
Subscribe to be the first to get our expert-written articles and tutorials for developers!
All fields are required