简体   繁体   中英

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. What I am trying to do is that I have a table called ContentTable. This ContentTable has different columns and rows and one of the columns is using EntityId's.

在此处输入图片说明

In my method I receive from somewhere a list of ID's in a List. 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. 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. Also for each entity it issues a single T-SQL Delete statement to delete the entity.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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