4

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 RemoveRange error 2 errro 3 EF Designer form database

Yasir Aslam
  • 477
  • 1
  • 5
  • 9

7 Answers7

8

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

Andy Nichols
  • 2,952
  • 2
  • 20
  • 36
5

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);
İsmet Alkan
  • 5,361
  • 3
  • 41
  • 64
Mike_G
  • 16,237
  • 14
  • 70
  • 101
  • correct. But no version restriction was given in the question. – Mike_G Oct 30 '14 at 13:36
  • @YasirAslam Are you sure it's EF4.5 or not .Net Framework 4.5? I don't see that version of EF in the MS list(http://msdn.microsoft.com/en-us/data/jj574253.aspx). – Terence Oct 31 '14 at 07:01
  • sorry my version is 5.0 i am new in asp.net. please check my post i update with my error screenshots. – Yasir Aslam Nov 01 '14 at 05:40
1
dbContext.Database.ExecuteSqlCommand("delete from VehicleProperties where EngineId = {0}", id);

this is the only time saving way... Check Answer Here

Community
  • 1
  • 1
Adnan Ahmed
  • 844
  • 6
  • 19
1

my problem is due to foreign key check out my 2nd image show Exception. first remove child then remove parents

The DELETE statement conflicted with the REFERENCE

Solution i just go to that SQL Server Managment studio open foreign key and set Delete Rule :Cascade (in INSERT And UPDATE Spcification)

Yasir Aslam
  • 477
  • 1
  • 5
  • 9
0

You can do the following:

db.VehicleProperties.Where(a => a.EngineId == id).ToList().ForEach(db.tblA.DeleteObject);
db.SaveChanges();
İsmet Alkan
  • 5,361
  • 3
  • 41
  • 64
0

Update after requested information:

As per our inner exception details its quite clear that there is a foreign key constraint conflict.

What that means is, before deleting a key that is referred in other table as foreign key, you have to delete the dependent rows first. You can also remove the constraint causing error to keep the rows dependent on key.

More information about how to achieve it using EF is here


In case the number of items to be deleted is not significantly large, you can use what Andy Nichols suggested.

But when you want to delete hundreds and thousands of items, you would notice that method is not performant. I recently encounter one such case and changed my method to what's shown below:

    public void DeleteAll<T>(IEnumerable<T> items) where T : class
    {
        Guard.ArgumentNotNull(items, "items");

        var autoDetectChangesEnabledBefore = Configuration.AutoDetectChangesEnabled;
        var validateOnSaveEnabled = Configuration.ValidateOnSaveEnabled;

        // It is said to make the performance better.
        Configuration.AutoDetectChangesEnabled = false;
        Configuration.ValidateOnSaveEnabled = false;

        foreach (var item in items)
        {
            Set<T>().Attach(item);
            Set<T>().Remove(item);
        }

        SaveChanges();

        Configuration.AutoDetectChangesEnabled = autoDetectChangesEnabledBefore;
        Configuration.ValidateOnSaveEnabled = validateOnSaveEnabled;

    }

You can read about these flags here.

Turning both of these flags off has advantage and disadvantage. In my case it was serving more good (huge performance saving) then bad. Open for comments on if there will be any side effects (haven't seen any in last one month).

SBirthare
  • 5,117
  • 4
  • 34
  • 59
  • Not single answer is working mu record is less no more then 15 – Yasir Aslam Oct 30 '14 at 14:02
  • @YasirAslam - Check the innerException in exception dialog. I think there could be a constraint issue. Can you add your VehicleProperties entity in your post. – SBirthare Nov 01 '14 at 08:40
  • this is Exception :{"The DELETE statement conflicted with the REFERENCE constraint \"FK_VehicleEngine_VehicleModel\". The conflict occurred in database \"rapid\", table \"dbo.VehicleEngine\", column 'ModelId'.\r\nThe statement has been terminated."} – Yasir Aslam Nov 01 '14 at 12:01
0

When you want to delete one ROW use .First() OR FirstOrDefault()

var x = (from obj in db.Vehiclepropertie where obj.Engineid == id select obj).First();

db.VehicleProperties.Remove(x);

db.SaveChanges();

Note:- You can also use .ToList() or FirstOrDefault instead of First().

AND IF YOU WANT TO DELETE MORE THAN ONE ROW ON THE BASIS OF id THEN

var x = (from obj in db.Vehiclepropertie where obj.Engineid == id select obj).ToList();

db.Vehiclepropertie.RemoveRange(x); 

db.SaveChanges(); 
sheldonzy
  • 5,505
  • 9
  • 48
  • 86