score:2

Accepted answer

You could do something to the effect of

db.MatchUpdateQueues.DeleteOnSubmit(db.MatchUpdateQueues.Single(theItem => theItem == item));

Just a note as other answers hinted towards Attach.. you will not be able to use attach on a context other then the original context the item was received on unless the entity has been serialized.

score:0

Use:

aDataContext db = new aDataContext();
item = new MatchUpdateQueue { id=item.id }; // <- updated
db.MatchUpdateQueues.Attach(item);
db.MatchUpdateQueues.DeleteOnSubmit(item);
db.SubmitChanges();

Since you are using a new datacontext it doesn't know that the object is already in the db.

score:0

Try wrapping the entire inside of the while loop in a using statement for a single data context:

Queue<MatchUpdateQueue> waiting = new Queue<MatchUpdateQueue>();
events.WriteEntry("matchqueue worker thread started");
while (!stop)
{
    using (var db = new aDataContext())
    {
      if (waiting.Count == 0)
      {
        /* grab any new items available */
           List<MatchUpdateQueue> freshitems = db.MatchUpdateQueues
                                                 .OrderBy(item => item.id)
                                                 .ToList();
           foreach (MatchUpdateQueue item in freshitems)
                waiting.Enqueue(item);
      }
      ...
   }
}

score:0

Remove the first db.Dispose() dispose. It can be the problem code because the entities keep a reference to their data context, so you don't want to dispose it while you are still be working with the instances. This won't affect connections, as they are open/closed only when doing operations that need them.

Also don't dispose the second data context like that, since an exception won't call that dispose code anyway. Use the using keyword, which will make sure to call dispose whether or not an exception occurs. Also grab the item from the db to delete it (to avoid having to serialize/deserialize/attach).

using (aDataContext db = new aDataContext())
{
   var dbItem = db.MatchUpdateQueues.Single(i => i.Id == item.Id);
   db.MatchUpdateQueues.DeleteOnSubmit(dbItem);
   db.SubmitChanges();
}

score:0

try this if your TEntity's (here Area) Primary Key is of type Identity column; Just it, without any change in your SP or Model:

public void InitForm()
{
    'bnsEntity is a BindingSource and cachedAreas is a List<Area> created from dataContext.Areas.ToList()
    bnsEntity.DataSource = cachedAreas;
    'A nominal ID
    newID = cachedAreas.LastOrDefault().areaID + 1;
    'grdEntity is a GridView
    grdEntity.DataSource = bnsEntity;
}

private void tsbNew_Click(object sender, EventArgs e)
{
    var newArea = new Area();
    newArea.areaID = newID++;
    dataContext.GetTable<Area>().InsertOnSubmit(newArea);
    bnsEntity.Add(newArea);
    grdEntity.MoveToNewRecord();
}

Related Articles