Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
This has been bugging me for a while, not sure how it works.

When working with an Entity Framework, suppose you create an instance of your context, run a query on it, grab an object from the query, pass that object somewhere else, then let the context go out of scope.

What happens to the retrieved object? Does it become detached? What if I modify it and want to write back to DB?

Here's a sample snippet code to explain what I mean:

(suppose MyObject is a class created by the Entity Framework designer to represent a particular DB table)

public class foo
{
   public MyObject currentMyObject;

   public void GetMyObject()
   {
       using (MyEFEntitiescontext = new MyEFEntities())
       {
            currentMyObject = context.MyObjects.FirstOrDefault();
       }
   }

   public void doSomething()
   {
      //Do some operations on the currentMyObject field

      //Save the currentMyObject back to the DB
   }
}

(note - I just threw the code together here, not in VS, so please ignore syntax errors :) )

If I run GetMyObject() first, and then run the function doSomething() second, what does the inside of that function see? How can it send changes made to the current object back to the DB?

Thanks,
Juliean.
Posted
Updated 10-Jun-11 7:16am
v2

Coincidentally I asked myself the same today!
What I found is that the object becomes detached. So changing any Properties to the EntityObject does not change its state anymore.
Since its the Context where you call the SaveChanges you would also never be able to save the EntityObject back to the database. The Context.StateManager could possibly alter the state of your EntityObject, but that is also Disposed off. So you effectively have an Untracked EntityObject. Untracked Entities are especially useful for binding to lookups like ComboBoxes where you want to select a value, but never change it.
If it would be possible to add the EntityObject to another Context I do not know (but I do not think so). But I think you could test that yourself easily enough :)
 
Share this answer
 
If Context goes out of scope, I think you cannot do the SaveChange() because The context is the one who know how to do that and the context also keep track about the state of objects.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900