I have a little program that uses ObjectListView to visualise the database information. Currently I am trying to add items and keep getting The operation cannot be completed because the DbContext has been disposed.
Which is highlighting the olvEntityTypes.AddObject(et);
line below.
Code:
string typeName = tbTypeName.Text;
string desc = tbDesc.Text;
EntityTypes et;
using (FCERTSModelContainer db = new FCERTSModelContainer())
{
// Create and save new row for the EntityTypes table.
et = new EntityTypes { EntityTypeName = typeName, Description = desc };
db.EntityTypes.Add(et);
db.SaveChanges();
olvEntityTypes.AddObject(et);
}
SaveChanges()
might also be closing the context, but trying to add the object before saving changes still throws the same error. olvEntityTypes.AddObject(et);
outside of the using
block is also a failure.Code:
var query = from ent in db.EntityTypes
orderby ent.EntityTypeName
select ent;
olvEntityTypes.SetObjects(query);
So I'm at a bit of a loss now as to why this is throwing errors and how to fix it.
It turns out the problem was the initial setting of objects for the objectlistview. I was using this piece of code;
var query = db.EntityTypes.OrderBy(eg => eg.EntityTypeName);
olvEntityTypes.SetObjects(query);
Which works fine, but is in a different using
block in my codebase and as such, a completely different DbContext.
If I convert the query to a List and then call SetObjects()
the entire program works without fault.