Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top