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?

4

2 回答 2

1

那是因为lstUsers不是实体。但是返回的实体lstUsers.First()是由 EF 跟踪的。

于 2011-09-29T09:23:07.710 回答
0

尝试添加.AsNoTracking()UsersDbSet 以将其与上下文分离。见下文。

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

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

StackOverflow 关于AsNoTracking .AsNoTracking() 有什么区别的问题?

于 2015-10-21T06:13:43.170 回答