How to delete a row from database using lambda linq?
10,996
Solution 1
Try something like this:
var friend = db.Friends.Where (x=>x.person.Id == user && x.Person1.Id == friend).FirstorDefault();
if (friend != null)
{
db.friends.Remove(friend);
db.SaveChanges()
}
if you have got multiple records than you can get rid of firstOrDefault and add .ToList() in the end. And than use db.friends.RemoveRange(friend)
it is much cleaner and hope this helps
Thanks
Solution 2
using where id in (1,2,3)
List<int> ids = new List<int>(){1,2,3};
var table1 = _context.table1.Where(x => ids.Contains(x.Id)).ToList();
if (table1 != null && table1.Count > 0) {
_context.table1.RemoveRange(table1 );
_context.SaveChanges();
}
Author by
Khaled A. Mousa
Updated on June 04, 2022Comments
-
Khaled A. Mousa almost 2 years
I want to perform a delete operation to unfriend a user in a certain android application I'm developing. The following method returns "Done" but the data doesn't delete from the table. What is the problem here?
public string deleteFriend(int user, int friend) { int i = db.Friends.Where(x => x.Person.Id == user && x.Person1.Id == friend).Select(x => x.Id).First(); var rec=db.Friends.ToList(); rec.RemoveAll(x=>rec.Any(xx=>xx.Id==i)); db.SaveChanges(); return "Done"; }
I'm working with Entity frame work LINQ.