none
LINQ-To-SQL update triggers invalid operation RRS feed

  • Question

  • I'm writing a fairly simple program that tracks inventory using LINQ-to-SQL Server.  Previously, I had no problems with writing insert/update code, but suddenly it stopped working.  Now when I try to save, it gives the error:  Operation is not valid due to the current state of the object.  It throws the exception when I try to update the field CategoryID.

    The foreign key is valid and the associations are set properly (as far as I can tell).  But I'm having difficulty finding what this error actually means.  Why does it only happen after I try to set this one field?

                    if (currentInventory == null)
                    {
                        MessageBox.Show("Error saving data. No current record.");
                        return false;
                    }
    
                    try
                    {
                        currentInventory.CanSubstitute = 1;
                        currentInventory.CategoryID = (int)(cboCategory.SelectedValue); (This triggers an error)
                        ....
    
                        LDC.SubmitChanges();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error saving data: \n" + ex.Message, Application.ProductName);
                        return false;
                    }
    Thursday, January 28, 2010 12:27 AM

Answers

  • I found the solution.  Apparently I need to set the association instead of just setting the foreign key.

    currentInventory.Category = LDC.Categories.SingleOrDefault(c => c.CategoryID == (int)(cboCategory.SelectedValue));
    
    instead of:
    
    currentInventory.CategoryID = (int)(cboCategory.SelectedValue);
    Thursday, January 28, 2010 9:54 PM