InvalidOperationException on InsertOnSubmit RRS feed

  • Question

  • Here's what I'm trying to do...

    I query my table with the following:


    var computers = (from c in db.Computers where c.Name == name select c).FirstOrDefault();


    I am expecting there to either be a single result or not a result. I essentially want to know if there is a matching record in the database.

    If the value is not null, I'm adding the object in "computers" to another collection. If the value is null, I'm creating a new Computer object and then attempting to insert it into the Computers database.

    I'm fairly certain this has something to do with the state of the DataContext, but I can't figure out how to get it to just ignore what's going on while I'm querying. I'm querying for objects from the database and I gather it is trying to track my changes, but I'm in fact making no changes to the object and I'm just doing other things with it. Then I try and do an insert on an object when it isn't in the database and when I go to insert it the DataContext is still tracking the old query... at least that's what I think is happening.

    So how can I avoid this?

    Friday, July 15, 2011 9:05 PM


  • I believe I figured it out. My Computers table didn't have a primary key. Once I set the primary key, it worked fine.
    • Proposed as answer by JA Reyes Sunday, July 17, 2011 3:31 PM
    • Marked as answer by Larcolais Gong Tuesday, August 2, 2011 2:49 AM
    Friday, July 15, 2011 9:28 PM