Click here to Skip to main content
15,907,497 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
hi i use this code for delete records in entity framework(several record)

C#
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!!)
Posted
Comments
Sergey Alexandrovich Kryukov 19-Sep-11 11:12am    
Why without "foreach"? How do you know that your performance leak is there?
Do you want to try exact same set of objects as in your sample but faster?
--SA

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:

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


—SA
 
Share this answer
 
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...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900