Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a row from database using lambda linq?

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.

like image 853
Khaled A. Mousa Avatar asked Mar 16 '26 03:03

Khaled A. Mousa


2 Answers

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

like image 92
Arun Kumar Avatar answered Mar 18 '26 18:03

Arun Kumar


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();
            }
like image 25
kuldeep chopra Avatar answered Mar 18 '26 18:03

kuldeep chopra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!