0
votes

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.

1
You say that ID is already in the database, I find that to be very unlikely. Put a breakpoint on your query, find the ID, and then manually check the database for it. Also, having a global variable which represents an item you're attaching to a EF context is a bad idea. - Rob
Sorry previous version wasn't understandable, I've added more lines of code. So Item is global variable and instantiated in BindObjectToControls method, then Save method is calling that method - Ibrokhimjon Saydakhmatov

1 Answers

0
votes

Well the problem is not with those 4 calls. The problem is that you are creating new object everytime when BindObjectToControls() method is called. Instead of creating a new Item() inside of BindObjectToControls(), Try to make inside constructor or somewhere else.