3

I am deleting the multiple records from the database using the .RemoveRange, but for that I have to fetch all the records first and then I pass them to the .RemoveRange, but I want to achieve that without fetching the records from the databas? any idea how to achieve that?

db.People.RemoveRange(just giving the ids or list of ids of people class);
Ali Nafees
  • 67
  • 10

2 Answers2

4

Try to use EntityFramework.Extended library, with it you can write:

db.People.Where(x => ids.Contains(x.Id)).Delete();
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26
  • Will it call to database only once and is it a fast way of doing that? – Ali Nafees Aug 29 '17 at 10:30
  • This would fetch the data from DB first, exactly the thing @Ali tries to avoid. – ViRuSTriNiTy Aug 29 '17 at 10:31
  • @AliNafees, yes it will not fetch data from database. You can read [this](https://github.com/zzzprojects/EntityFramework.Extended#batch-update-and-delete) – Slava Utesinov Aug 29 '17 at 10:32
  • @SlavaUtesinov It will not? Are you sure as .Where() is a condition and how should the library know which IDs are present without looking into the DB. – ViRuSTriNiTy Aug 29 '17 at 10:33
  • @ ViRuSTriNiTy I also have asked the same thing and let me check his link? – Ali Nafees Aug 29 '17 at 10:36
  • From documentation: Batch update and delete **eliminates the need to retrieve and load** an entity before modifying it – Slava Utesinov Aug 29 '17 at 10:37
  • Hey I have achieved that without using the Library and I would like to mark correct answer for the person who have said that do that by attaching first the entities. but thanks for your answer as well... – Ali Nafees Aug 29 '17 at 10:42
  • @AliNafees, attaching will work **only at case of Ids** filter, if you later will want to delete rows with custom filter, like `Where(x => x.Age > 20)`, it will not work. – Slava Utesinov Aug 29 '17 at 10:47
  • Yes but in this scnerio I was not needed to do for filtered first, and also I am avoiding installing the library first.main reason is I not want to install library – Ali Nafees Aug 29 '17 at 10:49
0

First create entities with new, assign the ID, then attach the entity like

db.People.Attach({your_entity_created_with_new})

and finally pass the entities to RemoveRange().

ViRuSTriNiTy
  • 5,017
  • 2
  • 32
  • 58