I’ve seen some posts here that look like mine, however I couldn’t find the answer to my specific problem.
The thing is that I’m trying to insert an entity into the DB using a nav. prop.
however I’m constantly getting: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
using (EntitiesDatabase context = new EntitiesDatabase())
{
if (UserHandler.Instance.User is Admin)
{
((Admin)UserHandler.Instance.User).ProjectManagers.Add(
new ProjectManager(firstNameTextBox.Text, lastNameTextBox.Text, usernameTextBox.Text, passwordTextBox.Text));
}
else if (UserHandler.Instance.User is ProjectManager)
{
((ProjectManager)UserHandler.Instance.User).Developers.Add(
new Developer(firstNameTextBox.Text, lastNameTextBox.Text, usernameTextBox.Text, passwordTextBox.Text));
}
context.SaveChanges();
}
The error exception is thrown at line 5-6 of the code (u.ProjectManagers.Add(new ProjectManager(...))
For clarity:
UserHandler is a singelton that holds the reference to the logged on user.
The user has a navigation property
public virtual ICollection<ProjectManager> ProjectManagers { get; set; }
That should actually insert the new project manager to the DB after I do SaveChanges() on the context.
I’ve done some simple tests on smaller projects (like the ones in the PluralSight tutorials) and it did work… for some reason these same lines do not work.
It really seems as if the new project manager I’m creating is being disposed before I try to insert it to the nav. prop. because I’m never getting to the save changes line…
From other answers I’ve seen, I guessed that the using statement for some reason disposes of things before it has reached the end bracket. I don’t get why…
Could someone point me in the right way?
BTW this is not homework guys, it’s a project of mine in which I am trying to learn C#, EF and other technologies.
It looks like the context you get the
Userinstance from are fetched in a different context, which are disposed.You have two options either use the same context, or attach the entity to the new context using ObjectContext.Attach like this: