实体框架中的DeleteObject加载整个表?
我遇到了实体框架的问题。我的代码尝试从表中删除 1 个或多个对象(大多少于 10 个)。
foreach (var val in vals)
{
int id = Convert.ToInt32(val);
var item = _container.Users.First(x => x.Id == id);
_container.Subscribers.DeleteObject(item);
}
_container.SaveChanges();
当前表“Users”大约有 20 000 行。当我运行代码时,如果它只尝试删除一个实体,则需要大约 10 秒。我调试了代码并查看了 SQL Profiler。一切都运行得很顺利,直到我们调用 DeleteObject() 方法。它将这个 sql 查询发送到数据库:
exec sp_executesql N'SELECT
-- Yada
FROM [dbo].[Users] AS [Extent1]
WHERE [Extent1].[UserListId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=1
为什么实体框架加载列表中的所有实体?斯特拉安格!
编辑:
当我将代码更改为:
int id = Convert.ToInt32(val);
Users u = new Users();
u.Id = Convert.ToInt32(val);
_container.Users.Attach(s);
_container.Users.DeleteObject(s);
它就像一个魅力!仍然。 “_container.Users.First(x => x.Id == id)”之前的代码确实去数据库找到了这个对象,但是之后的代码加载了整个表。
I have run into a problem with Entity Framework. My code tries to delete 1 or more objects mostly less then 10 from a table.
foreach (var val in vals)
{
int id = Convert.ToInt32(val);
var item = _container.Users.First(x => x.Id == id);
_container.Subscribers.DeleteObject(item);
}
_container.SaveChanges();
The current table "Users" has around 20 000 rows. When i run the code, if it only tries to delete one entity, it take around 10 secounds. I debuged the code and looked in the SQL Profiler. Everything runs smoothly until we hit the DeleteObject() method. It sends this sql query to the database:
exec sp_executesql N'SELECT
-- Yada
FROM [dbo].[Users] AS [Extent1]
WHERE [Extent1].[UserListId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=1
Why are entity framework loading all the entites in the list? Straaange!
EDIT:
When i changed the code to:
int id = Convert.ToInt32(val);
Users u = new Users();
u.Id = Convert.ToInt32(val);
_container.Users.Attach(s);
_container.Users.DeleteObject(s);
It works like a charm! Still. The code before "_container.Users.First(x => x.Id == id)" did go to the database to find this object, but the after that loaded the whole table.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
下面的语句无论如何都会调用您的数据库,这不是 EF 的一个奇怪的功能。
如果您在数据库中的用户表上创建了正确的主键,理想情况下不会花费更多时间。看来你缺少PK。
var item = _container.Users.First(x => x.Id == id);
Below statement anyways makes a call to your database, it is not a strange but feature of EF.
If you have proper primary key created on User table in your database, ideally it will not take more time. It seems you are missing PK.
var item = _container.Users.First(x => x.Id == id);