实体框架 - 分离对象列表时崩溃
我正在使用 EF 4.0 开发 winform 应用程序。
下面的代码因问题“无法分离对象,因为它未附加到 ObjectStateManager”而崩溃。当它尝试将列表与上下文分离时。
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;
}
令人惊讶的是,如果我像在注释代码中所做的那样从列表中仅分离一个对象,它就可以正常工作。
有人能告诉我,为什么它在尝试分离列表时会崩溃吗?另外,我们如何分离列表中的所有对象?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为
lstUsers
不是一个实体。但lstUsers.First()
返回的实体由 EF 跟踪。That is because
lstUsers
is not an entity. But the entity returned bylstUsers.First()
is tracked by EF.尝试将
.AsNoTracking()
添加到Users
DbSet 以将其与上下文分离。见下文。MSDN 参考
https://msdn.microsoft.com/en- us/library/gg679352(v=vs.103).aspx
有关
AsNoTracking
的 StackOverflow 问题.AsNoTracking() 有什么区别?
Try adding
.AsNoTracking()
to theUsers
DbSet to detach it from the context. See below.MSDN Reference
https://msdn.microsoft.com/en-us/library/gg679352(v=vs.103).aspx
StackOverflow question regarding
AsNoTracking
What difference does .AsNoTracking() make?