简体   繁体   English

如何使用LINQ创建数据库查询以通过具有ID列表并避免循环来擦除行

[英]How to create a database query with LINQ to erase rows by having a list of ID's and by avoiding loops

I am a newbie with LINQ so I would appreciate if you could explain thoroughly your answer. 我是LINQ的新手,所以如果您能彻底解释您的答案,我将不胜感激。 What I am trying to do is that I have a table called ContentTable. 我想做的是有一个名为ContentTable的表。 This ContentTable has different columns and rows and one of the columns is using EntityId's. 该ContentTable具有不同的列和行,并且其中一列正在使用EntityId。

在此处输入图片说明

In my method I receive from somewhere a list of ID's in a List. 在我的方法中,我从某处收到一个列表中的ID列表。 I don't want to iterate over this list and query the database for each ID because that would be expensive, but I want a query which uses the ID's in the list to match with the EntityID's in the table, and if there is such a match, I erase the whole row from the table. 我不想遍历此列表并为每个ID查询数据库,因为那会很昂贵,但是我想要一个使用列表中的ID与表中的EntityID匹配的查询,如果有这样的查询,匹配,我从表格中删除了整行。 May you kindly help me? 你能帮我吗? Thanks in advance! 提前致谢!

You can use Entity Framework Extensions to do that. 您可以使用实体框架扩展来做到这一点。 Something like: 就像是:

this.Container.Devices.Delete(
             o => o.Id == 1,
             o => o.Id == 2
        );

Some thing like this might help , however if the table is too big (millions) Linq to sql will lock the table. 这样的事情可能会有所帮助,但是,如果表太大(百万),Linq to sql将锁定表。 Also for each entity it issues a single T-SQL Delete statement to delete the entity. 同样,对于每个实体,它也会发出一个T-SQL Delete语句来删除该实体。

   public void DeleteContents(List<int> entityIds)
   {
        using (Yourcontext db = new Yourcontext())
        {
            IQueryable<ContentTable> contents = db.ContentTable.Where((x) => ids.Contains(x.EntityId));

            db.ProductComplianceRules.DeleteAllOnSubmit(contents);
        }
   }

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

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