Entity Framework - Crash on Detaching list of objects
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?
That is because lstUsers
is not an entity. But the entity returned by lstUsers.First()
is tracked by EF.
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?
精彩评论