How to Delete multiple records in Linq to Entity?

asp.net c# entity-framework linq sql

Question

I have a sql tblA:

id  int  (primary key)
fid  int 

data in table A are:

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

I delete single record using the code below:

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

I delete several records using the code below:

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

Exists a way to delete ZZZ-33-ZZZ from a Linq to Entity?

1
4
12/8/2013 11:03:30 AM

Accepted Answer

The next thing you can do is technically still a loop.

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

The SQL can also be called directly as an alternative.

11
12/8/2013 11:10:28 AM

Popular Answer

An extension is available at EntityFramework.Extended.

to remove every thing

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

also take a look at: How do I remove several rows at once using Entity Framework? (without foreach)



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow