Reputation: 11806
I have this code which uses Entity Framework 4.1 to access database entities:
public string Test()
{
Navigation nav = db.Navigations.FirstOrDefault();
List<Navigation> lNav = db.Navigations.ToList();
foreach (var item in lNav)
{
item.Label += " [Edited]";
}
return nav.Label;
}
When I run this in asp.net mvc it returns this:
News [Edited]
I expected it to return:
News
Because I thought my foreach
would only modify the contents of lNav
. Instead, it seems to modify all instances of the entity objects.
How can I modify lNav
without also modifying nav
?
Upvotes: 2
Views: 360
Reputation: 177173
Try AsNoTracking()
:
Navigation nav = db.Navigations.AsNoTracking().FirstOrDefault();
List<Navigation> lNav = db.Navigations.AsNoTracking().ToList();
This way loaded entities are not attached to the context and two different instances should be created for the first entity. By using AsNoTracking
you disable the identity mapping between key values of an entity and object references which is responsible for the behaviour you observed. (There can always only be one entity reference with a given key in the context and EF does not create a new object if you load an entity with the same key. Instead it returns the object which already exists in the context.)
Be aware that you cannot use this if you intent to update entities with the help of EFs change tracking mechanism. AsNoTracking()
is designed for readonly scenarios.
Upvotes: 1