Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how delete more than one record from database using Linq in asp.net mvc

This is the code for removing one record:

var vehicleProperty = db.VehicleProperties.Where(a => a.EngineId == id).ToList();
db.VehicleProperties.Remove(vehicleProperty);
db.SaveChanges();

If I want to remove more than one item then what I will do, for example, delete all where typeId = 4

I am trying with the code below, but causes an error.

var vp = db.VehicleProperties.Where(a => a.EngineId == id).ToList();
db.VehicleProperties.Remove(vp);
db.SaveChanges();

i am using entity framework Version=5.0.0.0 and using EF Designer form database (entity data model) i tried many code but errors please check my screenshots with code and error

error try with RemoveRangeerror 2errro 3EF Designer form database

like image 286
Yasir Aslam Avatar asked Dec 05 '22 23:12

Yasir Aslam


2 Answers

To do it through Linq to Entities you need to iterate through the collection removing them one at a time

var vps = db.VehicleProperties.Where(a => a.EngineId == id).ToList();
foreach (var vp in vps)
    db.VehicleProperties.Remove(vp);
db.SaveChanges();

Alternatively you can just pass in a SQL command as per this MSDN article

like image 55
Andy Nichols Avatar answered Dec 10 '22 13:12

Andy Nichols


From the related article:

var vp = db.VehicleProperties.Where(a => a.EngineId == id);
db.VehicleProperties.RemoveRange(vp);
db.SaveChanges();

or

db.Database.ExecuteSqlCommand("delete from VehicleProperties where EngineId = {0}", 4);
like image 27
Mike_G Avatar answered Dec 10 '22 13:12

Mike_G