Bulk deleting rows with RemoveRange() The Next CEO of Stack OverflowHow do I delete multiple rows in Entity Framework (without foreach)Could not load type 'System.Data.Entity.Core.Mapping.EntityContainerMapping'ADO.NET Entity Framework and identity columnsIt has a DefiningQuery but no InsertFunction element… errHow do I delete multiple rows in Entity Framework (without foreach)EF Code First “Invalid column name 'Discriminator'” but no inheritanceIntroducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?Delete a single record from Entity Framework?Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nullsDeleting an Entity with related data and Cascading Deletes defined in SQLServerDeleting multiple records at a time entities framework 5Entity RemoveRange delete all rows

Can the Reverse Gravity spell affect the Meteor Swarm spell?

Which organization defines CJK Unified Ideographs?

Implement the Thanos sorting algorithm

Is a stroke of luck acceptable after a series of unfavorable events?

Why did we only see the N-1 starfighters in one film?

How easy is it to start Magic from scratch?

Grabbing quick drinks

Why didn't Khan get resurrected in the Genesis Explosion?

If I blow insulation everywhere in my attic except the door trap, will heat escape through it?

Was a professor correct to chastise me for writing "Prof. X" rather than "Professor X"?

Unreliable Magic - Is it worth it?

Are there languages with no euphemisms?

How long to clear the 'suck zone' of a turbofan after start is initiated?

Does it take more energy to get to Venus or to Mars?

What does "Its cash flow is deeply negative" mean?

Failed to fetch jessie backports repository

Why do professional authors make "consistency" mistakes? And how to avoid them?

When airplanes disconnect from a tanker during air to air refueling, why do they bank so sharply to the right?

How did people program for Consoles with multiple CPUs?

Only print output after finding pattern

I believe this to be a fraud - hired, then asked to cash check and send cash as Bitcoin

How to make a variable always equal to the result of some calculations?

How to safely derail a train during transit?

Would this house-rule that treats advantage as a +1 to the roll instead (and disadvantage as -1) and allows them to stack be balanced?



Bulk deleting rows with RemoveRange()



The Next CEO of Stack OverflowHow do I delete multiple rows in Entity Framework (without foreach)Could not load type 'System.Data.Entity.Core.Mapping.EntityContainerMapping'ADO.NET Entity Framework and identity columnsIt has a DefiningQuery but no InsertFunction element… errHow do I delete multiple rows in Entity Framework (without foreach)EF Code First “Invalid column name 'Discriminator'” but no inheritanceIntroducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?Delete a single record from Entity Framework?Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nullsDeleting an Entity with related data and Cascading Deletes defined in SQLServerDeleting multiple records at a time entities framework 5Entity RemoveRange delete all rows










21















I am trying to delete multiple rows from a table.



In regular SQL Server, this would be simple as this:



DELETE FROM Table
WHERE
Table.Column = 'SomeRandomValue'
AND Table.Column2 = 'AnotherRandomValue'


In Entity Framework 6, they have introduced RemoveRange() method.

However, when I use it, rather than deleting rows using the where clauses that I provided, Entity Framework queries the database to get all rows that match the where clauses and delete them one by one using their primary keys.



Is this the current limitation of EntityFramework?
Or am I using RemoveRange() wrong?



Following is how I am using RemoveRange():



db.Tables.RemoveRange(
db.Tables
.Where(_ => _.Column == 'SomeRandomValue'
&& _.Column2 == 'AnotherRandomValue')
);









share|improve this question
























  • Is Tables the name of your repository?

    – Jeremy Holovacs
    Mar 3 '14 at 20:47






  • 3





    EntityFramework.Extended features a batch delete

    – paqogomez
    Mar 3 '14 at 20:51






  • 1





    check this out: stackoverflow.com/questions/2519866/…

    – Cristi Pufu
    Mar 3 '14 at 20:59






  • 1





    @CristiPufu & @paqogomez: Yeah, I am checking out EntityFramework.Extended. It is just unfortunate that MS built RemoveRange() functions but it still does looping.

    – Peter Han
    Mar 4 '14 at 23:24






  • 1





    I believe that RemoveRange was a community contribution that is slightly faster than looping through a bunch of entities yourself, but it's still deleting them one by one. There are no built-in support for batch delete in EF (other than running your own SQL)

    – ESG
    Mar 15 '15 at 23:12















21















I am trying to delete multiple rows from a table.



In regular SQL Server, this would be simple as this:



DELETE FROM Table
WHERE
Table.Column = 'SomeRandomValue'
AND Table.Column2 = 'AnotherRandomValue'


In Entity Framework 6, they have introduced RemoveRange() method.

However, when I use it, rather than deleting rows using the where clauses that I provided, Entity Framework queries the database to get all rows that match the where clauses and delete them one by one using their primary keys.



Is this the current limitation of EntityFramework?
Or am I using RemoveRange() wrong?



Following is how I am using RemoveRange():



db.Tables.RemoveRange(
db.Tables
.Where(_ => _.Column == 'SomeRandomValue'
&& _.Column2 == 'AnotherRandomValue')
);









share|improve this question
























  • Is Tables the name of your repository?

    – Jeremy Holovacs
    Mar 3 '14 at 20:47






  • 3





    EntityFramework.Extended features a batch delete

    – paqogomez
    Mar 3 '14 at 20:51






  • 1





    check this out: stackoverflow.com/questions/2519866/…

    – Cristi Pufu
    Mar 3 '14 at 20:59






  • 1





    @CristiPufu & @paqogomez: Yeah, I am checking out EntityFramework.Extended. It is just unfortunate that MS built RemoveRange() functions but it still does looping.

    – Peter Han
    Mar 4 '14 at 23:24






  • 1





    I believe that RemoveRange was a community contribution that is slightly faster than looping through a bunch of entities yourself, but it's still deleting them one by one. There are no built-in support for batch delete in EF (other than running your own SQL)

    – ESG
    Mar 15 '15 at 23:12













21












21








21


4






I am trying to delete multiple rows from a table.



In regular SQL Server, this would be simple as this:



DELETE FROM Table
WHERE
Table.Column = 'SomeRandomValue'
AND Table.Column2 = 'AnotherRandomValue'


In Entity Framework 6, they have introduced RemoveRange() method.

However, when I use it, rather than deleting rows using the where clauses that I provided, Entity Framework queries the database to get all rows that match the where clauses and delete them one by one using their primary keys.



Is this the current limitation of EntityFramework?
Or am I using RemoveRange() wrong?



Following is how I am using RemoveRange():



db.Tables.RemoveRange(
db.Tables
.Where(_ => _.Column == 'SomeRandomValue'
&& _.Column2 == 'AnotherRandomValue')
);









share|improve this question
















I am trying to delete multiple rows from a table.



In regular SQL Server, this would be simple as this:



DELETE FROM Table
WHERE
Table.Column = 'SomeRandomValue'
AND Table.Column2 = 'AnotherRandomValue'


In Entity Framework 6, they have introduced RemoveRange() method.

However, when I use it, rather than deleting rows using the where clauses that I provided, Entity Framework queries the database to get all rows that match the where clauses and delete them one by one using their primary keys.



Is this the current limitation of EntityFramework?
Or am I using RemoveRange() wrong?



Following is how I am using RemoveRange():



db.Tables.RemoveRange(
db.Tables
.Where(_ => _.Column == 'SomeRandomValue'
&& _.Column2 == 'AnotherRandomValue')
);






c# entity-framework entity-framework-6






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 '16 at 22:09







Peter Han

















asked Mar 3 '14 at 20:43









Peter HanPeter Han

3021313




3021313












  • Is Tables the name of your repository?

    – Jeremy Holovacs
    Mar 3 '14 at 20:47






  • 3





    EntityFramework.Extended features a batch delete

    – paqogomez
    Mar 3 '14 at 20:51






  • 1





    check this out: stackoverflow.com/questions/2519866/…

    – Cristi Pufu
    Mar 3 '14 at 20:59






  • 1





    @CristiPufu & @paqogomez: Yeah, I am checking out EntityFramework.Extended. It is just unfortunate that MS built RemoveRange() functions but it still does looping.

    – Peter Han
    Mar 4 '14 at 23:24






  • 1





    I believe that RemoveRange was a community contribution that is slightly faster than looping through a bunch of entities yourself, but it's still deleting them one by one. There are no built-in support for batch delete in EF (other than running your own SQL)

    – ESG
    Mar 15 '15 at 23:12

















  • Is Tables the name of your repository?

    – Jeremy Holovacs
    Mar 3 '14 at 20:47






  • 3





    EntityFramework.Extended features a batch delete

    – paqogomez
    Mar 3 '14 at 20:51






  • 1





    check this out: stackoverflow.com/questions/2519866/…

    – Cristi Pufu
    Mar 3 '14 at 20:59






  • 1





    @CristiPufu & @paqogomez: Yeah, I am checking out EntityFramework.Extended. It is just unfortunate that MS built RemoveRange() functions but it still does looping.

    – Peter Han
    Mar 4 '14 at 23:24






  • 1





    I believe that RemoveRange was a community contribution that is slightly faster than looping through a bunch of entities yourself, but it's still deleting them one by one. There are no built-in support for batch delete in EF (other than running your own SQL)

    – ESG
    Mar 15 '15 at 23:12
















Is Tables the name of your repository?

– Jeremy Holovacs
Mar 3 '14 at 20:47





Is Tables the name of your repository?

– Jeremy Holovacs
Mar 3 '14 at 20:47




3




3





EntityFramework.Extended features a batch delete

– paqogomez
Mar 3 '14 at 20:51





EntityFramework.Extended features a batch delete

– paqogomez
Mar 3 '14 at 20:51




1




1





check this out: stackoverflow.com/questions/2519866/…

– Cristi Pufu
Mar 3 '14 at 20:59





check this out: stackoverflow.com/questions/2519866/…

– Cristi Pufu
Mar 3 '14 at 20:59




1




1





@CristiPufu & @paqogomez: Yeah, I am checking out EntityFramework.Extended. It is just unfortunate that MS built RemoveRange() functions but it still does looping.

– Peter Han
Mar 4 '14 at 23:24





@CristiPufu & @paqogomez: Yeah, I am checking out EntityFramework.Extended. It is just unfortunate that MS built RemoveRange() functions but it still does looping.

– Peter Han
Mar 4 '14 at 23:24




1




1





I believe that RemoveRange was a community contribution that is slightly faster than looping through a bunch of entities yourself, but it's still deleting them one by one. There are no built-in support for batch delete in EF (other than running your own SQL)

– ESG
Mar 15 '15 at 23:12





I believe that RemoveRange was a community contribution that is slightly faster than looping through a bunch of entities yourself, but it's still deleting them one by one. There are no built-in support for batch delete in EF (other than running your own SQL)

– ESG
Mar 15 '15 at 23:12












8 Answers
8






active

oldest

votes


















3














I think we reached here a limitation of EF.
Sometimes you just have to use ExecuteSqlCommand to stay performant.






share|improve this answer






























    3














    What you are looking for is a Batch Delete Library which deletes multiple records in a database from a LINQ Query without loading entities.



    Multiple libraries supporting this feature exist.



    You can find the list here: Entity Framework Batch Delete Library



    Disclaimer: I'm the owner of the project Entity Framework Plus



    // using Z.EntityFramework.Plus; // Don't forget to include this.

    // DELETE directly in SQL (without loading entities)
    db.Tables.Where(_ => _.Column == 'SomeRandomValue'
    && _.Column2 == 'AnotherRandomValue')
    .Delete();

    // DELETE using a BatchSize
    db.Tables.Where(_ => _.Column == 'SomeRandomValue'
    && _.Column2 == 'AnotherRandomValue')
    .Delete(x => x.BatchSize = 1000);


    Wiki: EF+ Batch Delete






    share|improve this answer
































      1














      It's a bit broken, try



      db.Tables.RemoveRange(
      db.Tables
      .Where(_ => _.Column == 'SomeRandomValue'
      && _.Column2 == 'AnotherRandomeValue').AsEnumerable().ToList()
      );
      db.SaveChanges();





      share|improve this answer























      • Sorry, I still get the same result with this code. Entity Framework executes the inner query then loops through each row and deletes them.

        – Peter Han
        Mar 3 '14 at 22:25


















      1














      var db1 = db.Tables
      .Where(_ => _.Column == 'SomeRandomValue'
      && _.Column2 == 'AnotherRandomeValue').AsEnumerable().ToList();
      db.Tables.RemoveRange(db1);
      db.SaveChanges();


      Use an Variable to Store Removable list and pass it to RemoveRange().



      I Usually do like this, and That's Work.
      Hope This also work in your case.






      share|improve this answer


















      • 1





        Sorry, I still get the same result with this code. Entity Framework executes the inner query then loops through each row and deletes them.

        – Peter Han
        Apr 20 '15 at 19:43











      • If your table have foreign key, Specify in model using [Foreign] Attribute and use virtual

        – AKASH
        Apr 23 '15 at 14:34


















      0














      Why don't you just have an adapter to the database and just send the appropriate delete command like in your example?






      share|improve this answer


















      • 3





        I can. But that means I have to write the basic DELETE statement myself. That completely defeats the point of having an ORM. Also, what if I want a complex WHERE clause? By the time I have a super generic enough adapter that can handle bunch of different WHERE clause, I basically have built the ORM myself.

        – Peter Han
        Mar 18 '15 at 3:48


















      0














      Step back and think. Do you really want to download the records from the database in order to delete them? Just because you can doesn't make it a good idea.



      Perhaps you could consider deleting the items from the database with a stored procedure? EF also allows to do that...






      share|improve this answer




















      • 1





        I agree that stored procedure in this situation is the better solution. However, I also believe that is a short coming of EF. Deleting bunch of rows that match a certain criteria is basic CRUD. The fact that a stored procedure to do this better defeats the point of using an ORM.

        – Peter Han
        Apr 20 '15 at 19:29











      • There is something known as the "orm impedance mismatch", what it states in a nutshell is that databases are designed for - speed or CRUD operations - efficient size on disk - referential integrity and not just to keep data available after reboot or making sharing of data across system boundaries possible.

        – Walter Verhoeven
        Aug 16 '15 at 8:04



















      0














      I'm dealing with this myself, and agree with Adi - just use sql.



      I'm cleaning up old rows in a log table, and EF RemoveRange took 3 minutes to do the same thing this did in 3 seconds:



      DELETE FROM LogEntries WHERE DATEDIFF(day, GETDATE(), Date) < -6


      Date is the name of the column containing the date. To make it correct, use a parameter, of course, like this:



       context.Database.ExecuteSqlCommand
      ("DELETE FROM LogEntries WHERE DATEDIFF(day, GETDATE(), Date) < @DaysOld", new System.Data.SqlClient.SqlParameter(
      "DaysOld", - Settings.DaysToKeepDBLogEntries));


      Note that there are a lot of rows involved in my case. When I started the project and didn't have a lot of data, RemoveRange worked fine.






      share|improve this answer






























        0














        I have met this problem as well, this is my workaround with a library called entityframework.extended by LoreSoft (which you can get it from nuget package manager):



        1.You first query them your list.
        2.Then use .Delete(), which is a function from .extended library.



        var removeList = db.table.Where(_ => _.Column == 'SomeRandomValue'&& _.Column2 == 'AnotherRandomValue') 
        removeList .Delete();


        Note: According to Entity Framework EF extended, as of the time writing, this entityframework.extended is deprecated. Therefore one might need to consider entityframework plus library. While i have not tested on the plus extension, but i can confirmed working it works using .extended library.






        share|improve this answer

























        • You should probably explain .Delete() comes from an external library and is not part of entity framework

          – Ashley Medway
          Mar 9 at 10:06











        • thanks! i have edited my answer.

          – csamleong
          Mar 9 at 15:43











        • @csamleong, there are multiple comments and answers in this question that points to Entity Framework Extended. The goal of my question was to see if there is a vanilla EF way of doing this. Based on the answers I got, there isn't. While I have just given up on this issue and moved on, it's nice to see this question is still bothering a lot of people. Hopefully EF will figure something out soon or adopt EF extended into its own offering.

          – Peter Han
          Mar 10 at 8:17











        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f22157005%2fbulk-deleting-rows-with-removerange%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        8 Answers
        8






        active

        oldest

        votes








        8 Answers
        8






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        3














        I think we reached here a limitation of EF.
        Sometimes you just have to use ExecuteSqlCommand to stay performant.






        share|improve this answer



























          3














          I think we reached here a limitation of EF.
          Sometimes you just have to use ExecuteSqlCommand to stay performant.






          share|improve this answer

























            3












            3








            3







            I think we reached here a limitation of EF.
            Sometimes you just have to use ExecuteSqlCommand to stay performant.






            share|improve this answer













            I think we reached here a limitation of EF.
            Sometimes you just have to use ExecuteSqlCommand to stay performant.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 27 '16 at 9:23









            AdiAdi

            3,63533550




            3,63533550























                3














                What you are looking for is a Batch Delete Library which deletes multiple records in a database from a LINQ Query without loading entities.



                Multiple libraries supporting this feature exist.



                You can find the list here: Entity Framework Batch Delete Library



                Disclaimer: I'm the owner of the project Entity Framework Plus



                // using Z.EntityFramework.Plus; // Don't forget to include this.

                // DELETE directly in SQL (without loading entities)
                db.Tables.Where(_ => _.Column == 'SomeRandomValue'
                && _.Column2 == 'AnotherRandomValue')
                .Delete();

                // DELETE using a BatchSize
                db.Tables.Where(_ => _.Column == 'SomeRandomValue'
                && _.Column2 == 'AnotherRandomValue')
                .Delete(x => x.BatchSize = 1000);


                Wiki: EF+ Batch Delete






                share|improve this answer





























                  3














                  What you are looking for is a Batch Delete Library which deletes multiple records in a database from a LINQ Query without loading entities.



                  Multiple libraries supporting this feature exist.



                  You can find the list here: Entity Framework Batch Delete Library



                  Disclaimer: I'm the owner of the project Entity Framework Plus



                  // using Z.EntityFramework.Plus; // Don't forget to include this.

                  // DELETE directly in SQL (without loading entities)
                  db.Tables.Where(_ => _.Column == 'SomeRandomValue'
                  && _.Column2 == 'AnotherRandomValue')
                  .Delete();

                  // DELETE using a BatchSize
                  db.Tables.Where(_ => _.Column == 'SomeRandomValue'
                  && _.Column2 == 'AnotherRandomValue')
                  .Delete(x => x.BatchSize = 1000);


                  Wiki: EF+ Batch Delete






                  share|improve this answer



























                    3












                    3








                    3







                    What you are looking for is a Batch Delete Library which deletes multiple records in a database from a LINQ Query without loading entities.



                    Multiple libraries supporting this feature exist.



                    You can find the list here: Entity Framework Batch Delete Library



                    Disclaimer: I'm the owner of the project Entity Framework Plus



                    // using Z.EntityFramework.Plus; // Don't forget to include this.

                    // DELETE directly in SQL (without loading entities)
                    db.Tables.Where(_ => _.Column == 'SomeRandomValue'
                    && _.Column2 == 'AnotherRandomValue')
                    .Delete();

                    // DELETE using a BatchSize
                    db.Tables.Where(_ => _.Column == 'SomeRandomValue'
                    && _.Column2 == 'AnotherRandomValue')
                    .Delete(x => x.BatchSize = 1000);


                    Wiki: EF+ Batch Delete






                    share|improve this answer















                    What you are looking for is a Batch Delete Library which deletes multiple records in a database from a LINQ Query without loading entities.



                    Multiple libraries supporting this feature exist.



                    You can find the list here: Entity Framework Batch Delete Library



                    Disclaimer: I'm the owner of the project Entity Framework Plus



                    // using Z.EntityFramework.Plus; // Don't forget to include this.

                    // DELETE directly in SQL (without loading entities)
                    db.Tables.Where(_ => _.Column == 'SomeRandomValue'
                    && _.Column2 == 'AnotherRandomValue')
                    .Delete();

                    // DELETE using a BatchSize
                    db.Tables.Where(_ => _.Column == 'SomeRandomValue'
                    && _.Column2 == 'AnotherRandomValue')
                    .Delete(x => x.BatchSize = 1000);


                    Wiki: EF+ Batch Delete







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Aug 22 '18 at 22:31

























                    answered Nov 11 '16 at 14:06









                    Jonathan MagnanJonathan Magnan

                    6,00021334




                    6,00021334





















                        1














                        It's a bit broken, try



                        db.Tables.RemoveRange(
                        db.Tables
                        .Where(_ => _.Column == 'SomeRandomValue'
                        && _.Column2 == 'AnotherRandomeValue').AsEnumerable().ToList()
                        );
                        db.SaveChanges();





                        share|improve this answer























                        • Sorry, I still get the same result with this code. Entity Framework executes the inner query then loops through each row and deletes them.

                          – Peter Han
                          Mar 3 '14 at 22:25















                        1














                        It's a bit broken, try



                        db.Tables.RemoveRange(
                        db.Tables
                        .Where(_ => _.Column == 'SomeRandomValue'
                        && _.Column2 == 'AnotherRandomeValue').AsEnumerable().ToList()
                        );
                        db.SaveChanges();





                        share|improve this answer























                        • Sorry, I still get the same result with this code. Entity Framework executes the inner query then loops through each row and deletes them.

                          – Peter Han
                          Mar 3 '14 at 22:25













                        1












                        1








                        1







                        It's a bit broken, try



                        db.Tables.RemoveRange(
                        db.Tables
                        .Where(_ => _.Column == 'SomeRandomValue'
                        && _.Column2 == 'AnotherRandomeValue').AsEnumerable().ToList()
                        );
                        db.SaveChanges();





                        share|improve this answer













                        It's a bit broken, try



                        db.Tables.RemoveRange(
                        db.Tables
                        .Where(_ => _.Column == 'SomeRandomValue'
                        && _.Column2 == 'AnotherRandomeValue').AsEnumerable().ToList()
                        );
                        db.SaveChanges();






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Mar 3 '14 at 22:08









                        TFDTFD

                        18.9k22747




                        18.9k22747












                        • Sorry, I still get the same result with this code. Entity Framework executes the inner query then loops through each row and deletes them.

                          – Peter Han
                          Mar 3 '14 at 22:25

















                        • Sorry, I still get the same result with this code. Entity Framework executes the inner query then loops through each row and deletes them.

                          – Peter Han
                          Mar 3 '14 at 22:25
















                        Sorry, I still get the same result with this code. Entity Framework executes the inner query then loops through each row and deletes them.

                        – Peter Han
                        Mar 3 '14 at 22:25





                        Sorry, I still get the same result with this code. Entity Framework executes the inner query then loops through each row and deletes them.

                        – Peter Han
                        Mar 3 '14 at 22:25











                        1














                        var db1 = db.Tables
                        .Where(_ => _.Column == 'SomeRandomValue'
                        && _.Column2 == 'AnotherRandomeValue').AsEnumerable().ToList();
                        db.Tables.RemoveRange(db1);
                        db.SaveChanges();


                        Use an Variable to Store Removable list and pass it to RemoveRange().



                        I Usually do like this, and That's Work.
                        Hope This also work in your case.






                        share|improve this answer


















                        • 1





                          Sorry, I still get the same result with this code. Entity Framework executes the inner query then loops through each row and deletes them.

                          – Peter Han
                          Apr 20 '15 at 19:43











                        • If your table have foreign key, Specify in model using [Foreign] Attribute and use virtual

                          – AKASH
                          Apr 23 '15 at 14:34















                        1














                        var db1 = db.Tables
                        .Where(_ => _.Column == 'SomeRandomValue'
                        && _.Column2 == 'AnotherRandomeValue').AsEnumerable().ToList();
                        db.Tables.RemoveRange(db1);
                        db.SaveChanges();


                        Use an Variable to Store Removable list and pass it to RemoveRange().



                        I Usually do like this, and That's Work.
                        Hope This also work in your case.






                        share|improve this answer


















                        • 1





                          Sorry, I still get the same result with this code. Entity Framework executes the inner query then loops through each row and deletes them.

                          – Peter Han
                          Apr 20 '15 at 19:43











                        • If your table have foreign key, Specify in model using [Foreign] Attribute and use virtual

                          – AKASH
                          Apr 23 '15 at 14:34













                        1












                        1








                        1







                        var db1 = db.Tables
                        .Where(_ => _.Column == 'SomeRandomValue'
                        && _.Column2 == 'AnotherRandomeValue').AsEnumerable().ToList();
                        db.Tables.RemoveRange(db1);
                        db.SaveChanges();


                        Use an Variable to Store Removable list and pass it to RemoveRange().



                        I Usually do like this, and That's Work.
                        Hope This also work in your case.






                        share|improve this answer













                        var db1 = db.Tables
                        .Where(_ => _.Column == 'SomeRandomValue'
                        && _.Column2 == 'AnotherRandomeValue').AsEnumerable().ToList();
                        db.Tables.RemoveRange(db1);
                        db.SaveChanges();


                        Use an Variable to Store Removable list and pass it to RemoveRange().



                        I Usually do like this, and That's Work.
                        Hope This also work in your case.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Mar 31 '15 at 8:19









                        AKASHAKASH

                        18813




                        18813







                        • 1





                          Sorry, I still get the same result with this code. Entity Framework executes the inner query then loops through each row and deletes them.

                          – Peter Han
                          Apr 20 '15 at 19:43











                        • If your table have foreign key, Specify in model using [Foreign] Attribute and use virtual

                          – AKASH
                          Apr 23 '15 at 14:34












                        • 1





                          Sorry, I still get the same result with this code. Entity Framework executes the inner query then loops through each row and deletes them.

                          – Peter Han
                          Apr 20 '15 at 19:43











                        • If your table have foreign key, Specify in model using [Foreign] Attribute and use virtual

                          – AKASH
                          Apr 23 '15 at 14:34







                        1




                        1





                        Sorry, I still get the same result with this code. Entity Framework executes the inner query then loops through each row and deletes them.

                        – Peter Han
                        Apr 20 '15 at 19:43





                        Sorry, I still get the same result with this code. Entity Framework executes the inner query then loops through each row and deletes them.

                        – Peter Han
                        Apr 20 '15 at 19:43













                        If your table have foreign key, Specify in model using [Foreign] Attribute and use virtual

                        – AKASH
                        Apr 23 '15 at 14:34





                        If your table have foreign key, Specify in model using [Foreign] Attribute and use virtual

                        – AKASH
                        Apr 23 '15 at 14:34











                        0














                        Why don't you just have an adapter to the database and just send the appropriate delete command like in your example?






                        share|improve this answer


















                        • 3





                          I can. But that means I have to write the basic DELETE statement myself. That completely defeats the point of having an ORM. Also, what if I want a complex WHERE clause? By the time I have a super generic enough adapter that can handle bunch of different WHERE clause, I basically have built the ORM myself.

                          – Peter Han
                          Mar 18 '15 at 3:48















                        0














                        Why don't you just have an adapter to the database and just send the appropriate delete command like in your example?






                        share|improve this answer


















                        • 3





                          I can. But that means I have to write the basic DELETE statement myself. That completely defeats the point of having an ORM. Also, what if I want a complex WHERE clause? By the time I have a super generic enough adapter that can handle bunch of different WHERE clause, I basically have built the ORM myself.

                          – Peter Han
                          Mar 18 '15 at 3:48













                        0












                        0








                        0







                        Why don't you just have an adapter to the database and just send the appropriate delete command like in your example?






                        share|improve this answer













                        Why don't you just have an adapter to the database and just send the appropriate delete command like in your example?







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Mar 15 '15 at 20:07









                        Shar1er80Shar1er80

                        8,12921424




                        8,12921424







                        • 3





                          I can. But that means I have to write the basic DELETE statement myself. That completely defeats the point of having an ORM. Also, what if I want a complex WHERE clause? By the time I have a super generic enough adapter that can handle bunch of different WHERE clause, I basically have built the ORM myself.

                          – Peter Han
                          Mar 18 '15 at 3:48












                        • 3





                          I can. But that means I have to write the basic DELETE statement myself. That completely defeats the point of having an ORM. Also, what if I want a complex WHERE clause? By the time I have a super generic enough adapter that can handle bunch of different WHERE clause, I basically have built the ORM myself.

                          – Peter Han
                          Mar 18 '15 at 3:48







                        3




                        3





                        I can. But that means I have to write the basic DELETE statement myself. That completely defeats the point of having an ORM. Also, what if I want a complex WHERE clause? By the time I have a super generic enough adapter that can handle bunch of different WHERE clause, I basically have built the ORM myself.

                        – Peter Han
                        Mar 18 '15 at 3:48





                        I can. But that means I have to write the basic DELETE statement myself. That completely defeats the point of having an ORM. Also, what if I want a complex WHERE clause? By the time I have a super generic enough adapter that can handle bunch of different WHERE clause, I basically have built the ORM myself.

                        – Peter Han
                        Mar 18 '15 at 3:48











                        0














                        Step back and think. Do you really want to download the records from the database in order to delete them? Just because you can doesn't make it a good idea.



                        Perhaps you could consider deleting the items from the database with a stored procedure? EF also allows to do that...






                        share|improve this answer




















                        • 1





                          I agree that stored procedure in this situation is the better solution. However, I also believe that is a short coming of EF. Deleting bunch of rows that match a certain criteria is basic CRUD. The fact that a stored procedure to do this better defeats the point of using an ORM.

                          – Peter Han
                          Apr 20 '15 at 19:29











                        • There is something known as the "orm impedance mismatch", what it states in a nutshell is that databases are designed for - speed or CRUD operations - efficient size on disk - referential integrity and not just to keep data available after reboot or making sharing of data across system boundaries possible.

                          – Walter Verhoeven
                          Aug 16 '15 at 8:04
















                        0














                        Step back and think. Do you really want to download the records from the database in order to delete them? Just because you can doesn't make it a good idea.



                        Perhaps you could consider deleting the items from the database with a stored procedure? EF also allows to do that...






                        share|improve this answer




















                        • 1





                          I agree that stored procedure in this situation is the better solution. However, I also believe that is a short coming of EF. Deleting bunch of rows that match a certain criteria is basic CRUD. The fact that a stored procedure to do this better defeats the point of using an ORM.

                          – Peter Han
                          Apr 20 '15 at 19:29











                        • There is something known as the "orm impedance mismatch", what it states in a nutshell is that databases are designed for - speed or CRUD operations - efficient size on disk - referential integrity and not just to keep data available after reboot or making sharing of data across system boundaries possible.

                          – Walter Verhoeven
                          Aug 16 '15 at 8:04














                        0












                        0








                        0







                        Step back and think. Do you really want to download the records from the database in order to delete them? Just because you can doesn't make it a good idea.



                        Perhaps you could consider deleting the items from the database with a stored procedure? EF also allows to do that...






                        share|improve this answer















                        Step back and think. Do you really want to download the records from the database in order to delete them? Just because you can doesn't make it a good idea.



                        Perhaps you could consider deleting the items from the database with a stored procedure? EF also allows to do that...







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Dec 2 '15 at 19:50









                        Crono

                        6,90922359




                        6,90922359










                        answered Apr 17 '15 at 17:57









                        Walter VerhoevenWalter Verhoeven

                        44146




                        44146







                        • 1





                          I agree that stored procedure in this situation is the better solution. However, I also believe that is a short coming of EF. Deleting bunch of rows that match a certain criteria is basic CRUD. The fact that a stored procedure to do this better defeats the point of using an ORM.

                          – Peter Han
                          Apr 20 '15 at 19:29











                        • There is something known as the "orm impedance mismatch", what it states in a nutshell is that databases are designed for - speed or CRUD operations - efficient size on disk - referential integrity and not just to keep data available after reboot or making sharing of data across system boundaries possible.

                          – Walter Verhoeven
                          Aug 16 '15 at 8:04













                        • 1





                          I agree that stored procedure in this situation is the better solution. However, I also believe that is a short coming of EF. Deleting bunch of rows that match a certain criteria is basic CRUD. The fact that a stored procedure to do this better defeats the point of using an ORM.

                          – Peter Han
                          Apr 20 '15 at 19:29











                        • There is something known as the "orm impedance mismatch", what it states in a nutshell is that databases are designed for - speed or CRUD operations - efficient size on disk - referential integrity and not just to keep data available after reboot or making sharing of data across system boundaries possible.

                          – Walter Verhoeven
                          Aug 16 '15 at 8:04








                        1




                        1





                        I agree that stored procedure in this situation is the better solution. However, I also believe that is a short coming of EF. Deleting bunch of rows that match a certain criteria is basic CRUD. The fact that a stored procedure to do this better defeats the point of using an ORM.

                        – Peter Han
                        Apr 20 '15 at 19:29





                        I agree that stored procedure in this situation is the better solution. However, I also believe that is a short coming of EF. Deleting bunch of rows that match a certain criteria is basic CRUD. The fact that a stored procedure to do this better defeats the point of using an ORM.

                        – Peter Han
                        Apr 20 '15 at 19:29













                        There is something known as the "orm impedance mismatch", what it states in a nutshell is that databases are designed for - speed or CRUD operations - efficient size on disk - referential integrity and not just to keep data available after reboot or making sharing of data across system boundaries possible.

                        – Walter Verhoeven
                        Aug 16 '15 at 8:04






                        There is something known as the "orm impedance mismatch", what it states in a nutshell is that databases are designed for - speed or CRUD operations - efficient size on disk - referential integrity and not just to keep data available after reboot or making sharing of data across system boundaries possible.

                        – Walter Verhoeven
                        Aug 16 '15 at 8:04












                        0














                        I'm dealing with this myself, and agree with Adi - just use sql.



                        I'm cleaning up old rows in a log table, and EF RemoveRange took 3 minutes to do the same thing this did in 3 seconds:



                        DELETE FROM LogEntries WHERE DATEDIFF(day, GETDATE(), Date) < -6


                        Date is the name of the column containing the date. To make it correct, use a parameter, of course, like this:



                         context.Database.ExecuteSqlCommand
                        ("DELETE FROM LogEntries WHERE DATEDIFF(day, GETDATE(), Date) < @DaysOld", new System.Data.SqlClient.SqlParameter(
                        "DaysOld", - Settings.DaysToKeepDBLogEntries));


                        Note that there are a lot of rows involved in my case. When I started the project and didn't have a lot of data, RemoveRange worked fine.






                        share|improve this answer



























                          0














                          I'm dealing with this myself, and agree with Adi - just use sql.



                          I'm cleaning up old rows in a log table, and EF RemoveRange took 3 minutes to do the same thing this did in 3 seconds:



                          DELETE FROM LogEntries WHERE DATEDIFF(day, GETDATE(), Date) < -6


                          Date is the name of the column containing the date. To make it correct, use a parameter, of course, like this:



                           context.Database.ExecuteSqlCommand
                          ("DELETE FROM LogEntries WHERE DATEDIFF(day, GETDATE(), Date) < @DaysOld", new System.Data.SqlClient.SqlParameter(
                          "DaysOld", - Settings.DaysToKeepDBLogEntries));


                          Note that there are a lot of rows involved in my case. When I started the project and didn't have a lot of data, RemoveRange worked fine.






                          share|improve this answer

























                            0












                            0








                            0







                            I'm dealing with this myself, and agree with Adi - just use sql.



                            I'm cleaning up old rows in a log table, and EF RemoveRange took 3 minutes to do the same thing this did in 3 seconds:



                            DELETE FROM LogEntries WHERE DATEDIFF(day, GETDATE(), Date) < -6


                            Date is the name of the column containing the date. To make it correct, use a parameter, of course, like this:



                             context.Database.ExecuteSqlCommand
                            ("DELETE FROM LogEntries WHERE DATEDIFF(day, GETDATE(), Date) < @DaysOld", new System.Data.SqlClient.SqlParameter(
                            "DaysOld", - Settings.DaysToKeepDBLogEntries));


                            Note that there are a lot of rows involved in my case. When I started the project and didn't have a lot of data, RemoveRange worked fine.






                            share|improve this answer













                            I'm dealing with this myself, and agree with Adi - just use sql.



                            I'm cleaning up old rows in a log table, and EF RemoveRange took 3 minutes to do the same thing this did in 3 seconds:



                            DELETE FROM LogEntries WHERE DATEDIFF(day, GETDATE(), Date) < -6


                            Date is the name of the column containing the date. To make it correct, use a parameter, of course, like this:



                             context.Database.ExecuteSqlCommand
                            ("DELETE FROM LogEntries WHERE DATEDIFF(day, GETDATE(), Date) < @DaysOld", new System.Data.SqlClient.SqlParameter(
                            "DaysOld", - Settings.DaysToKeepDBLogEntries));


                            Note that there are a lot of rows involved in my case. When I started the project and didn't have a lot of data, RemoveRange worked fine.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Feb 9 '17 at 19:02









                            user7369569user7369569

                            11




                            11





















                                0














                                I have met this problem as well, this is my workaround with a library called entityframework.extended by LoreSoft (which you can get it from nuget package manager):



                                1.You first query them your list.
                                2.Then use .Delete(), which is a function from .extended library.



                                var removeList = db.table.Where(_ => _.Column == 'SomeRandomValue'&& _.Column2 == 'AnotherRandomValue') 
                                removeList .Delete();


                                Note: According to Entity Framework EF extended, as of the time writing, this entityframework.extended is deprecated. Therefore one might need to consider entityframework plus library. While i have not tested on the plus extension, but i can confirmed working it works using .extended library.






                                share|improve this answer

























                                • You should probably explain .Delete() comes from an external library and is not part of entity framework

                                  – Ashley Medway
                                  Mar 9 at 10:06











                                • thanks! i have edited my answer.

                                  – csamleong
                                  Mar 9 at 15:43











                                • @csamleong, there are multiple comments and answers in this question that points to Entity Framework Extended. The goal of my question was to see if there is a vanilla EF way of doing this. Based on the answers I got, there isn't. While I have just given up on this issue and moved on, it's nice to see this question is still bothering a lot of people. Hopefully EF will figure something out soon or adopt EF extended into its own offering.

                                  – Peter Han
                                  Mar 10 at 8:17















                                0














                                I have met this problem as well, this is my workaround with a library called entityframework.extended by LoreSoft (which you can get it from nuget package manager):



                                1.You first query them your list.
                                2.Then use .Delete(), which is a function from .extended library.



                                var removeList = db.table.Where(_ => _.Column == 'SomeRandomValue'&& _.Column2 == 'AnotherRandomValue') 
                                removeList .Delete();


                                Note: According to Entity Framework EF extended, as of the time writing, this entityframework.extended is deprecated. Therefore one might need to consider entityframework plus library. While i have not tested on the plus extension, but i can confirmed working it works using .extended library.






                                share|improve this answer

























                                • You should probably explain .Delete() comes from an external library and is not part of entity framework

                                  – Ashley Medway
                                  Mar 9 at 10:06











                                • thanks! i have edited my answer.

                                  – csamleong
                                  Mar 9 at 15:43











                                • @csamleong, there are multiple comments and answers in this question that points to Entity Framework Extended. The goal of my question was to see if there is a vanilla EF way of doing this. Based on the answers I got, there isn't. While I have just given up on this issue and moved on, it's nice to see this question is still bothering a lot of people. Hopefully EF will figure something out soon or adopt EF extended into its own offering.

                                  – Peter Han
                                  Mar 10 at 8:17













                                0












                                0








                                0







                                I have met this problem as well, this is my workaround with a library called entityframework.extended by LoreSoft (which you can get it from nuget package manager):



                                1.You first query them your list.
                                2.Then use .Delete(), which is a function from .extended library.



                                var removeList = db.table.Where(_ => _.Column == 'SomeRandomValue'&& _.Column2 == 'AnotherRandomValue') 
                                removeList .Delete();


                                Note: According to Entity Framework EF extended, as of the time writing, this entityframework.extended is deprecated. Therefore one might need to consider entityframework plus library. While i have not tested on the plus extension, but i can confirmed working it works using .extended library.






                                share|improve this answer















                                I have met this problem as well, this is my workaround with a library called entityframework.extended by LoreSoft (which you can get it from nuget package manager):



                                1.You first query them your list.
                                2.Then use .Delete(), which is a function from .extended library.



                                var removeList = db.table.Where(_ => _.Column == 'SomeRandomValue'&& _.Column2 == 'AnotherRandomValue') 
                                removeList .Delete();


                                Note: According to Entity Framework EF extended, as of the time writing, this entityframework.extended is deprecated. Therefore one might need to consider entityframework plus library. While i have not tested on the plus extension, but i can confirmed working it works using .extended library.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Mar 9 at 15:42

























                                answered Mar 8 at 13:10









                                csamleongcsamleong

                                81112




                                81112












                                • You should probably explain .Delete() comes from an external library and is not part of entity framework

                                  – Ashley Medway
                                  Mar 9 at 10:06











                                • thanks! i have edited my answer.

                                  – csamleong
                                  Mar 9 at 15:43











                                • @csamleong, there are multiple comments and answers in this question that points to Entity Framework Extended. The goal of my question was to see if there is a vanilla EF way of doing this. Based on the answers I got, there isn't. While I have just given up on this issue and moved on, it's nice to see this question is still bothering a lot of people. Hopefully EF will figure something out soon or adopt EF extended into its own offering.

                                  – Peter Han
                                  Mar 10 at 8:17

















                                • You should probably explain .Delete() comes from an external library and is not part of entity framework

                                  – Ashley Medway
                                  Mar 9 at 10:06











                                • thanks! i have edited my answer.

                                  – csamleong
                                  Mar 9 at 15:43











                                • @csamleong, there are multiple comments and answers in this question that points to Entity Framework Extended. The goal of my question was to see if there is a vanilla EF way of doing this. Based on the answers I got, there isn't. While I have just given up on this issue and moved on, it's nice to see this question is still bothering a lot of people. Hopefully EF will figure something out soon or adopt EF extended into its own offering.

                                  – Peter Han
                                  Mar 10 at 8:17
















                                You should probably explain .Delete() comes from an external library and is not part of entity framework

                                – Ashley Medway
                                Mar 9 at 10:06





                                You should probably explain .Delete() comes from an external library and is not part of entity framework

                                – Ashley Medway
                                Mar 9 at 10:06













                                thanks! i have edited my answer.

                                – csamleong
                                Mar 9 at 15:43





                                thanks! i have edited my answer.

                                – csamleong
                                Mar 9 at 15:43













                                @csamleong, there are multiple comments and answers in this question that points to Entity Framework Extended. The goal of my question was to see if there is a vanilla EF way of doing this. Based on the answers I got, there isn't. While I have just given up on this issue and moved on, it's nice to see this question is still bothering a lot of people. Hopefully EF will figure something out soon or adopt EF extended into its own offering.

                                – Peter Han
                                Mar 10 at 8:17





                                @csamleong, there are multiple comments and answers in this question that points to Entity Framework Extended. The goal of my question was to see if there is a vanilla EF way of doing this. Based on the answers I got, there isn't. While I have just given up on this issue and moved on, it's nice to see this question is still bothering a lot of people. Hopefully EF will figure something out soon or adopt EF extended into its own offering.

                                – Peter Han
                                Mar 10 at 8:17

















                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f22157005%2fbulk-deleting-rows-with-removerange%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                                2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                                Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme