Iti Tyagi
Iti Tyagi

Reputation: 3661

How to use Delete all functionality in Linq

I am trying to delete records from EF by using this query:

 public void ClearAllLocks(Lock LockObj)
    {
        var Stf = context.Locks.First(S => S.UserId == LockObj.UserId);

        if (Stf == null)
        {
            return;
        }
        context.Locks.DeleteObject(Stf);
        context.SaveChanges();
    }

But I am only able to delete the first record and I know the reason as well (as I am using First), what should I write instead of First so that all the entries can be deleted.

Upvotes: 1

Views: 167

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

public void ClearAllLocks(Lock LockObj)
{
    var locksToDelete = context.Locks.Where(s => s.UserId == LockObj.UserId);

    foreach(var stf in locksToDelete)
       context.Locks.DeleteObject(stf);

    context.SaveChanges();
}

Also you can use EntityFramework.Extended (search at NuGet):

public void ClearAllLocks(Lock LockObj)
{
    context.Locks.Delete(s => s.UserId == LockObj.UserId);        
    context.SaveChanges();
}

Upvotes: 2

Related Questions