C# – LINQ Query Issue, Sequence contains no elements


I'm trying to update a single record in a table, but when I run .Firstordefault(), I get the error: "Object reference not set to an instance of an object.", and if use it with .First(), I get "Sequence contains no elements".

Using it another place, its working fine, but this time its causing errors.

Here's the code:

public class AllownceDetails
  public int ta_id{get;set;}
  public int tvrid{get;set;}
  public DateTime ofDate{get;set;}
  public string status{get;set;}
  public string userid {get;set;}
//Update Method
public void Update(AllownceDetails Allowncedtl)

        var ta = (from a in ce.tbl_tvrallownce
                  where a.tvrid == Allowncedtl.tvrid 
                   //error: Sequence contains no elements

                  select a).SingleOrDefault();

        ta.status = Allowncedtl.status; 
                   //error:Object reference not set to an instance of an object


Best Solution

The query must not be returning any data. Run a profiler on the SQL database to see the physical query being executed and try to execute it manually against the database to see what the data looks like. You probably have to adjust the query (or the data) to get the results you're looking for.

"Sequence contains no elements" is basically LINQ's way of telling you that you're trying to reference an element from a list that doesn't have anything. So calls to things like .First() or .Single() can't find anything, hence the error.

When you change the calls to something like .FirstOrDefault() or .SingleOrDefault() then it will go with "default" value for that type, and for reference types the default is null. So if you set something to null and then try to call a method on it, you'll get object reference not set to an instance of an object.