27

I have Table like the following image:

enter image description here

how can I delete all records of table using Entity FrameWork based on ProjectId ?

Benafsh Yalda
  • 396
  • 1
  • 5
  • 13
  • possible duplicate of [How do I delete multiple rows in Entity Framework (without foreach)](http://stackoverflow.com/questions/2519866/how-do-i-delete-multiple-rows-in-entity-framework-without-foreach) – markpsmith Nov 28 '14 at 16:44
  • 2
    I don't care with foreach or with out foreach I want a good way to delete records based on ProjectId – Benafsh Yalda Nov 28 '14 at 16:45

3 Answers3

82

This one liner will do it:

  db.ProRel.RemoveRange(db.ProRel.Where(c => c.ProjectId == Project_id));
codegeek
  • 32,236
  • 12
  • 63
  • 63
MJ X
  • 8,506
  • 12
  • 74
  • 99
  • 2
    Great and really simple and Perfect answer thanks very much it worked perfect – Benafsh Yalda Nov 28 '14 at 17:37
  • No problem I am happy to solved your problem. – MJ X Nov 28 '14 at 17:46
  • 2
    Simple and elegant solution, thanks! – Nimblejoe Sep 02 '15 at 23:29
  • not all the EF version support `RemoveRange()` if this is the case use Jesse Carter's answer instead – Djeroen Oct 23 '15 at 18:50
  • 2
    What @AtulChaudhary said. RemoveRange doesn't take an IQueriable so all it's doing is retrieving to the client all the data you want to delete, and then enumerating it. What's really required is a way of passing to the DB a condition that defines what you want to delete and have that done by the database without pointlessly copying all that data to the client. – Neutrino Nov 01 '17 at 14:02
  • 2
    Elegant solution, thanks –  Jan 10 '20 at 15:18
  • 1
    Best one liner so far. Don't for get to add db.SaveChanges(); – Waller Dec 03 '20 at 21:48
16
context.Projects.Where(p => p.ProjectId == projectId)
               .ToList().ForEach(p => context.Projects.Remove(p));
context.SaveChanges();

Taken from this very similar post (which should probably be marked as duplicate).

Community
  • 1
  • 1
Jesse Carter
  • 20,062
  • 7
  • 64
  • 101
6

You can use DbSet.RemoveRange() and pass in an IEnumerable<Model>.

You build a list of models with ProjectId and pass them in RemoveRange() using the data context. Finally, call SaveChanges().

beautifulcoder
  • 10,832
  • 3
  • 19
  • 29