且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在实体框架中删除

更新时间:2022-10-18 14:46:36

我没有发现foreach有问题,但是尝试携带SaveChanges跳出循环.如果您确实有与foreach相关的性能泄漏,那么***反复进行SaveChanges.无需为每个对象重复此操作.

试试:

  foreach ( var  @object 标签中)
   objLib.TagsField.Context.DeleteObject(@object);
objLib.SaveChanges(); 



—SA



EntityFramework没有提供任何需要删除实体列表的功能...当您调用DeleteObject时,它只是标记应在SaveChanges上删除实体...

因此,即使在EF级别中有一个功能,例如

DeleteObjects(IList< object> toBeDeleted)...它必须遍历每个元素以标记为已删除吗?

如果您遇到性能问题,这不是因为您正在使用foreach,而是因为您在side foreach中调用SaveChanges ...我想对SaveChanges的调用必须遍历整个上下文,以检查要考虑的实体是什么更新或删除..这显然需要时间吗?

正如SAKryukov所提到的,***一次调用SaveChanges.

希望这对您有帮助...


hi i use this code for delete records in entity framework(several record)

var tag = from t in objLib.TagsField where t.Book_ID_FK == id select t;
         foreach (var t in tag)
         {
             objLib.TagsField.Context.DeleteObject(t);
             objLib.SaveChanges();
         }



how i delete it without use for each this code ( it Takes time!!)

I see nothing wrong with foreach, but try to carry SaveChanges out of the loop. If you really have a performance leak related to foreach, it''s rather in repeated SaveChanges. There is no need to repeat it for each object.

Try:

foreach (var @object in tag)
   objLib.TagsField.Context.DeleteObject(@object);
objLib.SaveChanges();



—SA


Hi
EntityFramework has not provided any function that takes list of entities to delete...When you call DeleteObject it just marks that entity should be deleted on SaveChanges...

So even if there is a function in EF level like

DeleteObjects(IList<object> toBeDeleted)...it has to loop through each element to mark as deleted right?

If you are facing performance issue, this is not because you are using foreach, it is because you are calling SaveChanges in side foreach... I guess call to SaveChanges has to go through whole context to check what are the entities to be consider for update or delete..obviuosly this takes time right?

As SAKryukov mentioned it is better call SaveChanges in one-go.

Hope this helps you...