I'm using Entity Framework. Here is my code to update data :
public bool UpdateProblem(Problem problem)
{
if (problem == null) {
throw new ArgumentException("Cannot add a null entity");
}
MathHubModelContainer ctx = new MathHubModelContainer();
ctx.Configuration.LazyLoadingEnabled = false;
ctx.Configuration.ProxyCreationEnabled = false;
DbEntityEntry attachtedEntrys = ctx.Entry(problem);
// Find Currently Entity Entry in Context
DbEntityEntry entry = ctx.Entry<Post>(problem);
// if does not attatch yet.
if (entry.State == EntityState.Detached)
{
// new entity here is wrapped by proxy
Problem attachedProblem = ctx.Set<Problem>().Find(problem.Id);
if (attachedProblem != null)
{
// get curently DBEntityEntry with AttachedProblem
DbEntityEntry attachtedEntry = ctx.Entry(attachedProblem);
attachtedEntry.CurrentValues.SetValues(problem);
attachtedEntry.State = EntityState.Modified;
}
else
{
//entry.State = EntityState.Modified;
//entry.CurrentValues.SetValues(problem);
return false;
}
}
else
{
// this entity has been attached to current context
entry.CurrentValues.SetValues(problem);
entry.State = EntityState.Modified;
}
ctx.SaveChanges();
return true;
}
Everything works fine (that I have checked database and I see all data has been saved successfully). But when I retrieve data :
DBContext ctx = new DBContext();
public Problem GetProblemById(int id)
{
return ctx.Posts.OfType<Problem>().FirstOrDefault(t => t.Id == id);
}
Because I have used above DBContext object to get problem object, so, currently in that DBContext already contains one problem. so, when i retrieve problem, it will get old one, not the new object I have updated.
But if I changed to this :
public Problem GetProblemById(int id)
{
MathHubModelContainer ctx = new MathHubModelContainer();
return ctx.Posts.OfType<Problem>().FirstOrDefault(t => t.Id == id);
}
Everything works fine. So my question is :
How can i use just one DBContext object (not to create new one when calling), but still update data of object when another DBContext update it ?
Thanks :)