How to Delete multiple records in Linq to Entity?

I have a tblA in sql:

id  int  (primary key)
fid  int

data in tblA is:

1   1
2   1
3   2
4   2
5   3
6   3

i delete one record by following code:

DatabaseEntities obj = new DatabaseEntities();
int i = 2;
tblA t = obj.tblA.Where(x => x.fid == i).FirstOrDefault();
obj.DeleteObject(t);
obj.SaveChanges();

i delete multiple records by following code:

DatabaseEntities obj = new DatabaseEntities();
int i = 2;
while (obj.tblA.Where(x => x.fid == i).Count() != 0)
{
   tblA t = obj.tblA.Where(x => x.fid == i).FirstOrDefault();
   obj.DeleteObject(t);
   obj.SaveChanges();
}

Is there any solution for delete multiple records in linq to entity?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can do the following, which is technically still a loop.

obj.tblA.Where(x => x.fid == i).ToList().ForEach(obj.tblA.DeleteObject);
obj.SaveChanges();

The alternative is calling the SQL directly.

Method 2

There is a extension provided at EntityFramework.Extended

to delete all object

//delete all users where FirstName matches
context.Users.Delete(u => u.FirstName == "firstname");

Additionally look into : How do I delete multiple rows in Entity Framework (without foreach)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x