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 ?

2

3 Answers 3

82

This one liner will do it:

  db.ProRel.RemoveRange(db.ProRel.Where(c => c.ProjectId == Project_id));
Sign up to request clarification or add additional context in comments.

6 Comments

Great and really simple and Perfect answer thanks very much it worked perfect
No problem I am happy to solved your problem.
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.
Elegant solution, thanks
Best one liner so far. Don't for get to add db.SaveChanges();
|
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).

8 Comments

I think you forgot to actually delete.
@KirkWoll ForEach(context.Projects.DeleteObject); deletes them
um...no, that's not right.
Oh, I see, DeleteObject lives on ObjectContext. (The current and now standard DbContext doesn't have that method)
The solution I'm working on is in an older version of EF that doesn't support RemoveRange. I ended up using this as it was the next best solution I found.
|
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().

4 Comments

I am new to ASP.Net MVC and Entity Framework could you give example in detail my Table Name is ProvRel how can I delete multiple records from this table Based on ProjectId
No problem, I will need to see more code. I need your data context and data model.
private MYDBContext db = new MYDBContext();
not all the EF version support RemoveRange() if this is the case use Jesse Carter's answer instead

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.