Error: Sequence contains no elements


  • Hi NG,


    I'm using the following statemtn to get a record from my database


    Code Snippet
    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"
           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 Settings\oaytekin\Desktop\LINQSamples\Sample0040\Program.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()



    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");




    Thx for your help,

    Ozgur Aytekin



    Monday, May 28, 2007 4:51 PM


  • Use SingleOrDefault. It returns null if the row isn't found.



    Monday, May 28, 2007 4:54 PM

All replies

  • Use SingleOrDefault. It returns null if the row isn't found.



    Monday, May 28, 2007 4:54 PM
  • Thx Anders



    Monday, May 28, 2007 5:15 PM
  • I'm having the following problem with those two methods.

    I have a record in db which has some numeric fields as height, lenght, width. For some reasons, when I call
    MyContext.MyTable.SingleOrDefault(elem => elem.ID == ID) (ID is a given param in my method) it returns my entity , but those numeric fields have the value 0.

    If I call MyContext.MyTable.Single(elem => elem.ID == ID) it brings me the entity with the correct values, but there is also the posibility that i don't have the specified ID and then it throws the exception with "Sequence has no elements".

    I would like to use SingleOrDefault and still to get my values .. can anyone explain how to do it ?
    Monday, June 09, 2008 12:49 PM
  • The best way is to check whether the record exists or not by using the "Count" method.

    int recCount = MyContext.MyTable.Count(elem => elem.ID == ID);


    if (recCount > 0)


    TableObject tblObject = (TableObject) MyContext.MyTable.SingleOrDefault(elem => elem.ID == ID)





    Hope this helps (It did solve my problem).


    Tuesday, July 22, 2008 12:56 AM
  • Hi all,

    I didn't understand Entity Framework. If everything is object why i couldn't reach all properties ???
    Let me explain with an example.


    Entities ctx = new Entities();


    var postInfo = ctx.Posts.Where(p => p.IsOpenForUserQuestions).FirstOrDefault();



    (postInfo != null)



    string temp = string.Format("{0} {1} {2} <b>{3}</b><br />", postInfo.InterViewedDate, postInfo.Corporates.CorporateName, postInfo.JobTitles.Title, postInfo.PersonFullName);

    ltrNextPost.Text = temp;


    I am getting "object reference not set to an  instance of ... " error. But i get result from SQL belowed query.

    SELECT Posts.PostID, Posts.PersonFullName, Posts.Url, Corporates.CorporateName, JobTitles.Title, Posts.InterViewedDate



    Posts INNER JOIN


    ON Posts.JobID = JobTitles.JobTitleID INNER JOIN


    ON Posts.CorporateID = Corporates.CorporateID



    (Posts.IsOpenForUserQuestions = 1)

    OK. When i want to do that with join syntax in EF





    var thepost = from post in ctx.Posts


                       join jobtitles in ctx.JobTitles on post.JobTitles


    i can't because there is no JobTitleID property so i can't make a relation. It has a relation already that's why i see post.JobTitles insted of JobTitleID

    What is the logic in EF?

    Thanks in advance.

    sometimes i feel my self like a "." that i am at end of an meaned sentences or begining of it.
    Friday, June 05, 2009 6:17 PM
  • Using SingleOrDefault works with LINQ to SQL but does not work with LINQ to Entities
    Friday, August 21, 2009 11:35 PM
  • I found that in LINQ To Entities (Entity Framework), that it is something similar
    it's FirstOrDefault()
    Friday, August 21, 2009 11:36 PM
  •  FirstOrDefault()
    Friday, August 21, 2009 11:37 PM
  • You can also use : FirstOrDefault()
    Prabhat Mohan
    Wednesday, February 03, 2010 1:35 PM
  • Worked for me. Many Thanks.
    Tuesday, April 10, 2012 1:36 PM