How to Bulk Update records in Entity Framework?












10















I am trying to bulk update records using Entity Framework. I have tried Entity Framework.Extensions Update method.



The Update method is able to bulk update for a set of records with same set of update values.



Example:



           Id -  Quantity
Record 1 - A - 10
Record 2 - B - 20
Record 3 - C - 30


We can bulk update all the above records by simple calling



Records.Update(new => Record { Quantity = 100 });


How can I bulk update each record with different quantity using Entityframework.Extensions or in any other approach, which completes the bulk update faster?










share|improve this question

























  • Update each record with individual data means one statement for each record. The fastest way is to execute all that statements within a single transaction, but it will take some time. How do you do the update process for now?

    – Sir Rufo
    May 29 '17 at 6:23











  • currently we are using entity framework , looping through each records update the db entity properties and then save changes, this process will be executed for all the 50,000 records which is taking lot more time.

    – Ujjwal27
    May 29 '17 at 6:31













  • The question then is where are the values coming from for the update? Are they from another table? Or are they a function of the original value (e.g. 2x)? Can every row have a different value or can you update groups of rows using EF-extended?

    – Phil
    May 29 '17 at 18:47













  • The records are coming after the UI has has processed data and sent to service for an update, yes every row can have different value. tried EF-Extended but i was able to update group of records with same value but not each records with different values in Bulk format.

    – Ujjwal27
    May 30 '17 at 5:44













  • If the values are coming from the UI then your entities are unattached. So essentially every record will get selected and then updated which will definitely slow things down considerably. The answer from @GrégoryBourgin might be able to solve this without bringing in another library. Since each row needs a different value you will need individual update statements - but if you call SaveChanges after modifying each manually attached record then you should get a batch update and no roundtripping of the data.

    – Robert Petz
    May 31 '17 at 0:03
















10















I am trying to bulk update records using Entity Framework. I have tried Entity Framework.Extensions Update method.



The Update method is able to bulk update for a set of records with same set of update values.



Example:



           Id -  Quantity
Record 1 - A - 10
Record 2 - B - 20
Record 3 - C - 30


We can bulk update all the above records by simple calling



Records.Update(new => Record { Quantity = 100 });


How can I bulk update each record with different quantity using Entityframework.Extensions or in any other approach, which completes the bulk update faster?










share|improve this question

























  • Update each record with individual data means one statement for each record. The fastest way is to execute all that statements within a single transaction, but it will take some time. How do you do the update process for now?

    – Sir Rufo
    May 29 '17 at 6:23











  • currently we are using entity framework , looping through each records update the db entity properties and then save changes, this process will be executed for all the 50,000 records which is taking lot more time.

    – Ujjwal27
    May 29 '17 at 6:31













  • The question then is where are the values coming from for the update? Are they from another table? Or are they a function of the original value (e.g. 2x)? Can every row have a different value or can you update groups of rows using EF-extended?

    – Phil
    May 29 '17 at 18:47













  • The records are coming after the UI has has processed data and sent to service for an update, yes every row can have different value. tried EF-Extended but i was able to update group of records with same value but not each records with different values in Bulk format.

    – Ujjwal27
    May 30 '17 at 5:44













  • If the values are coming from the UI then your entities are unattached. So essentially every record will get selected and then updated which will definitely slow things down considerably. The answer from @GrégoryBourgin might be able to solve this without bringing in another library. Since each row needs a different value you will need individual update statements - but if you call SaveChanges after modifying each manually attached record then you should get a batch update and no roundtripping of the data.

    – Robert Petz
    May 31 '17 at 0:03














10












10








10


4






I am trying to bulk update records using Entity Framework. I have tried Entity Framework.Extensions Update method.



The Update method is able to bulk update for a set of records with same set of update values.



Example:



           Id -  Quantity
Record 1 - A - 10
Record 2 - B - 20
Record 3 - C - 30


We can bulk update all the above records by simple calling



Records.Update(new => Record { Quantity = 100 });


How can I bulk update each record with different quantity using Entityframework.Extensions or in any other approach, which completes the bulk update faster?










share|improve this question
















I am trying to bulk update records using Entity Framework. I have tried Entity Framework.Extensions Update method.



The Update method is able to bulk update for a set of records with same set of update values.



Example:



           Id -  Quantity
Record 1 - A - 10
Record 2 - B - 20
Record 3 - C - 30


We can bulk update all the above records by simple calling



Records.Update(new => Record { Quantity = 100 });


How can I bulk update each record with different quantity using Entityframework.Extensions or in any other approach, which completes the bulk update faster?







c# entity-framework linq bulkupdate entity-framework-extended






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 8:10









S.Akbari

30.3k93673




30.3k93673










asked May 26 '17 at 6:18









Ujjwal27Ujjwal27

3103926




3103926













  • Update each record with individual data means one statement for each record. The fastest way is to execute all that statements within a single transaction, but it will take some time. How do you do the update process for now?

    – Sir Rufo
    May 29 '17 at 6:23











  • currently we are using entity framework , looping through each records update the db entity properties and then save changes, this process will be executed for all the 50,000 records which is taking lot more time.

    – Ujjwal27
    May 29 '17 at 6:31













  • The question then is where are the values coming from for the update? Are they from another table? Or are they a function of the original value (e.g. 2x)? Can every row have a different value or can you update groups of rows using EF-extended?

    – Phil
    May 29 '17 at 18:47













  • The records are coming after the UI has has processed data and sent to service for an update, yes every row can have different value. tried EF-Extended but i was able to update group of records with same value but not each records with different values in Bulk format.

    – Ujjwal27
    May 30 '17 at 5:44













  • If the values are coming from the UI then your entities are unattached. So essentially every record will get selected and then updated which will definitely slow things down considerably. The answer from @GrégoryBourgin might be able to solve this without bringing in another library. Since each row needs a different value you will need individual update statements - but if you call SaveChanges after modifying each manually attached record then you should get a batch update and no roundtripping of the data.

    – Robert Petz
    May 31 '17 at 0:03



















  • Update each record with individual data means one statement for each record. The fastest way is to execute all that statements within a single transaction, but it will take some time. How do you do the update process for now?

    – Sir Rufo
    May 29 '17 at 6:23











  • currently we are using entity framework , looping through each records update the db entity properties and then save changes, this process will be executed for all the 50,000 records which is taking lot more time.

    – Ujjwal27
    May 29 '17 at 6:31













  • The question then is where are the values coming from for the update? Are they from another table? Or are they a function of the original value (e.g. 2x)? Can every row have a different value or can you update groups of rows using EF-extended?

    – Phil
    May 29 '17 at 18:47













  • The records are coming after the UI has has processed data and sent to service for an update, yes every row can have different value. tried EF-Extended but i was able to update group of records with same value but not each records with different values in Bulk format.

    – Ujjwal27
    May 30 '17 at 5:44













  • If the values are coming from the UI then your entities are unattached. So essentially every record will get selected and then updated which will definitely slow things down considerably. The answer from @GrégoryBourgin might be able to solve this without bringing in another library. Since each row needs a different value you will need individual update statements - but if you call SaveChanges after modifying each manually attached record then you should get a batch update and no roundtripping of the data.

    – Robert Petz
    May 31 '17 at 0:03

















Update each record with individual data means one statement for each record. The fastest way is to execute all that statements within a single transaction, but it will take some time. How do you do the update process for now?

– Sir Rufo
May 29 '17 at 6:23





Update each record with individual data means one statement for each record. The fastest way is to execute all that statements within a single transaction, but it will take some time. How do you do the update process for now?

– Sir Rufo
May 29 '17 at 6:23













currently we are using entity framework , looping through each records update the db entity properties and then save changes, this process will be executed for all the 50,000 records which is taking lot more time.

– Ujjwal27
May 29 '17 at 6:31







currently we are using entity framework , looping through each records update the db entity properties and then save changes, this process will be executed for all the 50,000 records which is taking lot more time.

– Ujjwal27
May 29 '17 at 6:31















The question then is where are the values coming from for the update? Are they from another table? Or are they a function of the original value (e.g. 2x)? Can every row have a different value or can you update groups of rows using EF-extended?

– Phil
May 29 '17 at 18:47







The question then is where are the values coming from for the update? Are they from another table? Or are they a function of the original value (e.g. 2x)? Can every row have a different value or can you update groups of rows using EF-extended?

– Phil
May 29 '17 at 18:47















The records are coming after the UI has has processed data and sent to service for an update, yes every row can have different value. tried EF-Extended but i was able to update group of records with same value but not each records with different values in Bulk format.

– Ujjwal27
May 30 '17 at 5:44







The records are coming after the UI has has processed data and sent to service for an update, yes every row can have different value. tried EF-Extended but i was able to update group of records with same value but not each records with different values in Bulk format.

– Ujjwal27
May 30 '17 at 5:44















If the values are coming from the UI then your entities are unattached. So essentially every record will get selected and then updated which will definitely slow things down considerably. The answer from @GrégoryBourgin might be able to solve this without bringing in another library. Since each row needs a different value you will need individual update statements - but if you call SaveChanges after modifying each manually attached record then you should get a batch update and no roundtripping of the data.

– Robert Petz
May 31 '17 at 0:03





If the values are coming from the UI then your entities are unattached. So essentially every record will get selected and then updated which will definitely slow things down considerably. The answer from @GrégoryBourgin might be able to solve this without bringing in another library. Since each row needs a different value you will need individual update statements - but if you call SaveChanges after modifying each manually attached record then you should get a batch update and no roundtripping of the data.

– Robert Petz
May 31 '17 at 0:03












3 Answers
3






active

oldest

votes


















12





+50









If you don't want to use an SQL statement, you can use the Attach method in order to update an entity without having to load it first :



using (myDbEntities db = new myDbEntities())
{
try
{
//disable detection of changes to improve performance
db.Configuration.AutoDetectChangesEnabled = false;

//for all the entities to update...
MyObjectEntity entityToUpdate = new MyObjectEntity() {Id=123, Quantity=100};
db.MyObjectEntity.Attach(entityToUpdate);

//then perform the update
db.SaveChanges();
}
finally
{
//re-enable detection of changes
db.Configuration.AutoDetectChangesEnabled = true;
}
}





share|improve this answer





















  • 8





    If you only want to update one property of an entity, do you have to set all the other properties to their existing values, as will it nullify anything that's not set?

    – James Love
    Sep 15 '17 at 10:55





















10














Use ExecuteSqlCommand:



using (yourDbEntities db = new yourDbEntities())
{
db.Database.ExecuteSqlCommand("UPDATE YourTABLE SET Quantity = {0} WHERE Id = {1}", quantity, id);
}


Or ExecuteStoreCommand:



yourDbContext.ExecuteStoreCommand("UPDATE YourTABLE SET Quantity = {0} WHERE Id = {1}", quantity, id);





share|improve this answer

































    1














    Bulk Update can be done in three steps with simple EF instead of separate extension methods :-




    • Load all the entities first.

    • Foreach on each entity and change its field values.

    • After Foreach save the context changes once.


    This will send multiple Update queries in single batch.






    share|improve this answer



















    • 4





      You are describing a batch update, not a bulk update, which is slow for 50k rows.

      – Phil
      May 29 '17 at 18:49






    • 1





      Plus for posterity to anyone reading this in the future - this would select every record from the database into memory then operate on each one individually in C# before sending all of them back as sequential update calls in one batch SQL command. EDIT: For this question, this is probably the only way you can do this using Entity Framework, but considering each record has to roundtrip instead of just get updated there are better solutions than using EF here

      – Robert Petz
      May 30 '17 at 23:50













    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%2f44194877%2fhow-to-bulk-update-records-in-entity-framework%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    12





    +50









    If you don't want to use an SQL statement, you can use the Attach method in order to update an entity without having to load it first :



    using (myDbEntities db = new myDbEntities())
    {
    try
    {
    //disable detection of changes to improve performance
    db.Configuration.AutoDetectChangesEnabled = false;

    //for all the entities to update...
    MyObjectEntity entityToUpdate = new MyObjectEntity() {Id=123, Quantity=100};
    db.MyObjectEntity.Attach(entityToUpdate);

    //then perform the update
    db.SaveChanges();
    }
    finally
    {
    //re-enable detection of changes
    db.Configuration.AutoDetectChangesEnabled = true;
    }
    }





    share|improve this answer





















    • 8





      If you only want to update one property of an entity, do you have to set all the other properties to their existing values, as will it nullify anything that's not set?

      – James Love
      Sep 15 '17 at 10:55


















    12





    +50









    If you don't want to use an SQL statement, you can use the Attach method in order to update an entity without having to load it first :



    using (myDbEntities db = new myDbEntities())
    {
    try
    {
    //disable detection of changes to improve performance
    db.Configuration.AutoDetectChangesEnabled = false;

    //for all the entities to update...
    MyObjectEntity entityToUpdate = new MyObjectEntity() {Id=123, Quantity=100};
    db.MyObjectEntity.Attach(entityToUpdate);

    //then perform the update
    db.SaveChanges();
    }
    finally
    {
    //re-enable detection of changes
    db.Configuration.AutoDetectChangesEnabled = true;
    }
    }





    share|improve this answer





















    • 8





      If you only want to update one property of an entity, do you have to set all the other properties to their existing values, as will it nullify anything that's not set?

      – James Love
      Sep 15 '17 at 10:55
















    12





    +50







    12





    +50



    12




    +50





    If you don't want to use an SQL statement, you can use the Attach method in order to update an entity without having to load it first :



    using (myDbEntities db = new myDbEntities())
    {
    try
    {
    //disable detection of changes to improve performance
    db.Configuration.AutoDetectChangesEnabled = false;

    //for all the entities to update...
    MyObjectEntity entityToUpdate = new MyObjectEntity() {Id=123, Quantity=100};
    db.MyObjectEntity.Attach(entityToUpdate);

    //then perform the update
    db.SaveChanges();
    }
    finally
    {
    //re-enable detection of changes
    db.Configuration.AutoDetectChangesEnabled = true;
    }
    }





    share|improve this answer















    If you don't want to use an SQL statement, you can use the Attach method in order to update an entity without having to load it first :



    using (myDbEntities db = new myDbEntities())
    {
    try
    {
    //disable detection of changes to improve performance
    db.Configuration.AutoDetectChangesEnabled = false;

    //for all the entities to update...
    MyObjectEntity entityToUpdate = new MyObjectEntity() {Id=123, Quantity=100};
    db.MyObjectEntity.Attach(entityToUpdate);

    //then perform the update
    db.SaveChanges();
    }
    finally
    {
    //re-enable detection of changes
    db.Configuration.AutoDetectChangesEnabled = true;
    }
    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited May 31 '17 at 12:56

























    answered May 29 '17 at 17:24









    Grégory BourginGrégory Bourgin

    704316




    704316








    • 8





      If you only want to update one property of an entity, do you have to set all the other properties to their existing values, as will it nullify anything that's not set?

      – James Love
      Sep 15 '17 at 10:55
















    • 8





      If you only want to update one property of an entity, do you have to set all the other properties to their existing values, as will it nullify anything that's not set?

      – James Love
      Sep 15 '17 at 10:55










    8




    8





    If you only want to update one property of an entity, do you have to set all the other properties to their existing values, as will it nullify anything that's not set?

    – James Love
    Sep 15 '17 at 10:55







    If you only want to update one property of an entity, do you have to set all the other properties to their existing values, as will it nullify anything that's not set?

    – James Love
    Sep 15 '17 at 10:55















    10














    Use ExecuteSqlCommand:



    using (yourDbEntities db = new yourDbEntities())
    {
    db.Database.ExecuteSqlCommand("UPDATE YourTABLE SET Quantity = {0} WHERE Id = {1}", quantity, id);
    }


    Or ExecuteStoreCommand:



    yourDbContext.ExecuteStoreCommand("UPDATE YourTABLE SET Quantity = {0} WHERE Id = {1}", quantity, id);





    share|improve this answer






























      10














      Use ExecuteSqlCommand:



      using (yourDbEntities db = new yourDbEntities())
      {
      db.Database.ExecuteSqlCommand("UPDATE YourTABLE SET Quantity = {0} WHERE Id = {1}", quantity, id);
      }


      Or ExecuteStoreCommand:



      yourDbContext.ExecuteStoreCommand("UPDATE YourTABLE SET Quantity = {0} WHERE Id = {1}", quantity, id);





      share|improve this answer




























        10












        10








        10







        Use ExecuteSqlCommand:



        using (yourDbEntities db = new yourDbEntities())
        {
        db.Database.ExecuteSqlCommand("UPDATE YourTABLE SET Quantity = {0} WHERE Id = {1}", quantity, id);
        }


        Or ExecuteStoreCommand:



        yourDbContext.ExecuteStoreCommand("UPDATE YourTABLE SET Quantity = {0} WHERE Id = {1}", quantity, id);





        share|improve this answer















        Use ExecuteSqlCommand:



        using (yourDbEntities db = new yourDbEntities())
        {
        db.Database.ExecuteSqlCommand("UPDATE YourTABLE SET Quantity = {0} WHERE Id = {1}", quantity, id);
        }


        Or ExecuteStoreCommand:



        yourDbContext.ExecuteStoreCommand("UPDATE YourTABLE SET Quantity = {0} WHERE Id = {1}", quantity, id);






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited May 26 '17 at 7:37

























        answered May 26 '17 at 6:21









        S.AkbariS.Akbari

        30.3k93673




        30.3k93673























            1














            Bulk Update can be done in three steps with simple EF instead of separate extension methods :-




            • Load all the entities first.

            • Foreach on each entity and change its field values.

            • After Foreach save the context changes once.


            This will send multiple Update queries in single batch.






            share|improve this answer



















            • 4





              You are describing a batch update, not a bulk update, which is slow for 50k rows.

              – Phil
              May 29 '17 at 18:49






            • 1





              Plus for posterity to anyone reading this in the future - this would select every record from the database into memory then operate on each one individually in C# before sending all of them back as sequential update calls in one batch SQL command. EDIT: For this question, this is probably the only way you can do this using Entity Framework, but considering each record has to roundtrip instead of just get updated there are better solutions than using EF here

              – Robert Petz
              May 30 '17 at 23:50


















            1














            Bulk Update can be done in three steps with simple EF instead of separate extension methods :-




            • Load all the entities first.

            • Foreach on each entity and change its field values.

            • After Foreach save the context changes once.


            This will send multiple Update queries in single batch.






            share|improve this answer



















            • 4





              You are describing a batch update, not a bulk update, which is slow for 50k rows.

              – Phil
              May 29 '17 at 18:49






            • 1





              Plus for posterity to anyone reading this in the future - this would select every record from the database into memory then operate on each one individually in C# before sending all of them back as sequential update calls in one batch SQL command. EDIT: For this question, this is probably the only way you can do this using Entity Framework, but considering each record has to roundtrip instead of just get updated there are better solutions than using EF here

              – Robert Petz
              May 30 '17 at 23:50
















            1












            1








            1







            Bulk Update can be done in three steps with simple EF instead of separate extension methods :-




            • Load all the entities first.

            • Foreach on each entity and change its field values.

            • After Foreach save the context changes once.


            This will send multiple Update queries in single batch.






            share|improve this answer













            Bulk Update can be done in three steps with simple EF instead of separate extension methods :-




            • Load all the entities first.

            • Foreach on each entity and change its field values.

            • After Foreach save the context changes once.


            This will send multiple Update queries in single batch.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered May 29 '17 at 16:52









            JaswinderJaswinder

            194




            194








            • 4





              You are describing a batch update, not a bulk update, which is slow for 50k rows.

              – Phil
              May 29 '17 at 18:49






            • 1





              Plus for posterity to anyone reading this in the future - this would select every record from the database into memory then operate on each one individually in C# before sending all of them back as sequential update calls in one batch SQL command. EDIT: For this question, this is probably the only way you can do this using Entity Framework, but considering each record has to roundtrip instead of just get updated there are better solutions than using EF here

              – Robert Petz
              May 30 '17 at 23:50
















            • 4





              You are describing a batch update, not a bulk update, which is slow for 50k rows.

              – Phil
              May 29 '17 at 18:49






            • 1





              Plus for posterity to anyone reading this in the future - this would select every record from the database into memory then operate on each one individually in C# before sending all of them back as sequential update calls in one batch SQL command. EDIT: For this question, this is probably the only way you can do this using Entity Framework, but considering each record has to roundtrip instead of just get updated there are better solutions than using EF here

              – Robert Petz
              May 30 '17 at 23:50










            4




            4





            You are describing a batch update, not a bulk update, which is slow for 50k rows.

            – Phil
            May 29 '17 at 18:49





            You are describing a batch update, not a bulk update, which is slow for 50k rows.

            – Phil
            May 29 '17 at 18:49




            1




            1





            Plus for posterity to anyone reading this in the future - this would select every record from the database into memory then operate on each one individually in C# before sending all of them back as sequential update calls in one batch SQL command. EDIT: For this question, this is probably the only way you can do this using Entity Framework, but considering each record has to roundtrip instead of just get updated there are better solutions than using EF here

            – Robert Petz
            May 30 '17 at 23:50







            Plus for posterity to anyone reading this in the future - this would select every record from the database into memory then operate on each one individually in C# before sending all of them back as sequential update calls in one batch SQL command. EDIT: For this question, this is probably the only way you can do this using Entity Framework, but considering each record has to roundtrip instead of just get updated there are better solutions than using EF here

            – Robert Petz
            May 30 '17 at 23:50




















            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%2f44194877%2fhow-to-bulk-update-records-in-entity-framework%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

            MongoDB - Not Authorized To Execute Command

            How to fix TextFormField cause rebuild widget in Flutter

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith