vini
vini

Reputation: 4740

Sequence contains no records in Entity Framework

StackTrace = "   at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)\r\n   at System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__0[TResult](IEnumerable`1 sequence)\r\n   at System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult]...

It was working before all of a sudden not able to get any records from the table using entity framework

Don't know what is the issue it worked fine before haven't made any changes to the edmx file either

  public bool SetClientIdForUser(string username, string clientId)
    {
        aspnet_Users aspnetUsers = _objVaccinationContext.aspnet_Users.First(t => t.UserName == username);
        //aspnetUsers.Client_Id = clientId;
        aspnetUsers.Client_id = clientId;
        var entry = _objVaccinationContext.Entry(aspnetUsers);
        entry.State = EntityState.Modified;
        _objVaccinationContext.SaveChanges();
        return true;
    }

enter image description here

CONNECTION STRING : <add name="ChildVaccinationEntities" connectionString="metadata=res://*/ChildVaccinationContext.ChildVaccination.csdl|res://*/ChildVaccinationContext.ChildVaccination.ssdl|res://*/ChildVaccinationContext.ChildVaccination.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=localhost;initial catalog=CVSUAT;user id=sa;password=Password123;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

NOTE: the first record in my table is the record i want to get so cannot use any other function

Upvotes: 0

Views: 1416

Answers (2)

Matten
Matten

Reputation: 17603

The First method of LINQ throws an exception if the filtered sequence does not at least contain one element. So if the username is not found within your database, this line of code throws an error. You can use FirstOrDefault and check for null.

Upvotes: 1

scartag
scartag

Reputation: 17680

You can use FirstOrDefault then check for null

aspnet_Users aspnetUsers = _objVaccinationContext.aspnet_Users.FirstOrDefault(t => t.UserName == username);

if(aspnetUsers != null)
{

  //do your stuff
return true
}

else
{
return false
}

Upvotes: 2

Related Questions