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();





Not getting "Delete" or "DeleteObject" reference.
– Partha
Aug 27 at 5:52





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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)