0

I am working on a winform application with EF 4.0.

Below code, crashes with issue 'The object cannot be detached because it is not attached to the ObjectStateManager.' when it tries to detach the list from context.

public List<Users> FindUserList()
        {
            List<Users> lstUsers = null;
            var q = from c in context.Users
                    select c;
            lstUsers = q.ToList();
            //context.Detach(lstUsers.First());
            context.Detach(lstUsers);
            return lstUsers;
        }

Surprisingly, it works fine if I detach only one object from the list as I have done in the commented code.

Can someone tell, why it crashes when it tries to detach a list? Also, How can we detach all objects of the list?

user899055
  • 301
  • 1
  • 6
  • 17

2 Answers2

1

That is because lstUsers is not an entity. But the entity returned by lstUsers.First() is tracked by EF.

Eranga
  • 32,181
  • 5
  • 97
  • 96
0

Try adding .AsNoTracking() to the Users DbSet to detach it from the context. See below.

List<Users> lstUsers = null;
var q = from c in context.Users.AsNoTracking()
       select c;
 lstUsers = q.ToList();
 return lstUsers;

MSDN Reference
https://msdn.microsoft.com/en-us/library/gg679352(v=vs.103).aspx

StackOverflow question regarding AsNoTracking What difference does .AsNoTracking() make?