简体   繁体   English

如何在asp.net mvc中使用Linq从数据库中删除多条记录

[英]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 如果我想删除多个项目,那么我将做什么,例如,删除所有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 我正在使用实体框架版本= 5.0.0.0并使用EF Designer表单数据库(实体数据模型)我尝试了很多代码但错误请检查我的截图与代码和错误

错误尝试使用RemoveRange错误2错误3EF Designer表单数据库

To do it through Linq to Entities you need to iterate through the collection removing them one at a time 要通过Linq to Entities执行此操作,您需要遍历集合,逐个删除它们

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 或者,您可以根据此MSDN文章传入SQL命令

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);
dbContext.Database.ExecuteSqlCommand("delete from VehicleProperties where EngineId = {0}", id);

这是唯一一次省时的方式...... 在这里查看答案

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 DELETE语句与REFERENCE冲突

Solution i just go to that SQL Server Managment studio open foreign key and set Delete Rule :Cascade (in INSERT And UPDATE Spcification) 解决方案我只是去那个SQL Server Managment studio打开外键并设置Delete Rule:Cascade(在INSERT和UPDATE Spcification中)

You can do the following: 您可以执行以下操作:

db.VehicleProperties.Where(a => a.EngineId == id).ToList().ForEach(db.tblA.DeleteObject);
db.SaveChanges();

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 有关如何使用EF实现它的更多信息,请点击此处


In case the number of items to be deleted is not significantly large, you can use what Andy Nichols suggested. 如果要删除的项目数量不是很大,您可以使用Andy Nichols建议的内容。

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). 如果有任何副作用(在过去一个月内没有看到任何副作用),请公开征求意见。

When you want to delete one ROW use .First() OR FirstOrDefault() 当你想删除一个ROW时使用.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(). 注意: - 您也可以使用.ToList()或FirstOrDefault而不是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(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM