When I try to retrieve an object from a local database, it throws an exception
Sequence contains no elements
However I have added sample data into database. What can cause this error?
private void BindObjectToControls()
{
Item = new Item();
//set values entered by user into UI to corresponding properties of the object
try
{
Item.Description = cbxType.Text.ToString() + ", " + tbxDesc.Text;
Item.Category = (string)cbxCategory.SelectedItem;
Item.Brand = (string)cbxBrand.SelectedItem;
Item.Price = (int)nudPrice.Value;
}
catch(NullReferenceException ex)
{
MessageBox.Show("Error" + ex);
}
}
private void Save()
{
BindObjectToControls();
ComputerUZEntities db = new ComputerUZEntities();
if (isNew)
{
db.Items.Add(Item);
}
else
{
Item myItem = (from ctx in db.Items where ctx.ItemID == Item.ItemID select ctx).Single();
//Item is global variable.
myItem.Description = Item.Description;
myItem.Category = Item.Category;
myItem.Brand = Item.Brand;
myItem.Price = Item.Price;
}
db.Items.SqlQuery(sql);
db.SaveChanges();
MessageBox.Show("Saved!");
this.Close();
}
P.S I have tried all 4 calls Single, SingleOrDefault, First, FirstOrDefault. None of them has worked.