开发者

DeleteObject from Entity Framework loads the whole table?

开发者 https://www.devze.com 2023-04-11 19:13 出处:网络
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.

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.


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);

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号