Linq ForEach to delete in mvc
Linq ForEach to delete in mvc
I want to delete multiple records using linq in my mvc application. I have written the following code
To store selected items in a list. I have written the following code
List<int> TaskIds = chkId.Select(x => int.Parse(x)).ToList();
I have written the following code to delete multiple records
db.Generals.Where(d => d.IID == TaskIds.ForEach(p => db.Generals.Remove(p.IID)));
But Remove(p.IID) is not a correct syntax. How could I find the write ID value for remove. Any clue
Thanks
2 Answers
2
You could try with this one:
db.Generals.Where(d => TaskIds.Contains(d.IID)).Delete();
or
db.Generals.Where(d => TaskIds.Contains(d.IID)).ToList().ForEach(db.DeleteObject);
db.SaveChanges();
sry, it is part of ObjectContext, not from DbContext. Here you are with DbContext
db.Generals.RemoveRange(db.Generals.Where(d => TaskIds.Contains(d.IID))); db.SaveChanges();
Or if you prefer with ForEach db.Generals.Where(d => TaskIds.Contains(d.IID)).ToList().ForEach(s => db.Generals.Remove(s));
– Selvirrr
Aug 27 at 7:16
db.Generals.RemoveRange(db.Generals.Where(d => TaskIds.Contains(d.IID))); db.SaveChanges();
db.Generals.Where(d => TaskIds.Contains(d.IID)).ToList().ForEach(s => db.Generals.Remove(s));
Thanks.It is working.
– Partha
Aug 27 at 7:41
Attach them and delete them. I assume IID is the key field.
foreach(int id in chkId.Select(x => int.Parse(x))
var general = new General IID = id ;
db.Generals.Attach(general);
db.Generals.Remove(general);
db.SaveChanges();
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Not getting "Delete" or "DeleteObject" reference.
– Partha
Aug 27 at 5:52