A second operation started on this context











up vote
3
down vote

favorite












In my Controller I execute another Void Function after the date saved to DB. But sometimes it's show this error :




A second operation started on this context before a previous
asynchronous operation completed. Use 'await' to ensure that any
asynchronous operations have completed before calling another method
on this context. Any instance members are not guaranteed to be thread
safe.




...and here is a sample of my controller :



public ActionResult All(Chapter chapter){

var x = db.Post.Where(p => p.PostID == chapter.PostID).FirstOrDefault();
if (x == null){return View(chapter);}

counter++;

db.Chapter.Add(chapter);
db.SaveChangesAsync();

savepost(chapter.PostID, counter);

return RedirectToAction("Index");
}


and here is the Void method:



public void savepost(int id,int counter)
{
var article = db.Post.Find(id);
article.LastUpdate = DateTime.Now;
article.ChapterCount = counter;

db.Entry(article).State = EntityState.Modified;
db.SaveChanges();
}


How i can solve this ?










share|improve this question




























    up vote
    3
    down vote

    favorite












    In my Controller I execute another Void Function after the date saved to DB. But sometimes it's show this error :




    A second operation started on this context before a previous
    asynchronous operation completed. Use 'await' to ensure that any
    asynchronous operations have completed before calling another method
    on this context. Any instance members are not guaranteed to be thread
    safe.




    ...and here is a sample of my controller :



    public ActionResult All(Chapter chapter){

    var x = db.Post.Where(p => p.PostID == chapter.PostID).FirstOrDefault();
    if (x == null){return View(chapter);}

    counter++;

    db.Chapter.Add(chapter);
    db.SaveChangesAsync();

    savepost(chapter.PostID, counter);

    return RedirectToAction("Index");
    }


    and here is the Void method:



    public void savepost(int id,int counter)
    {
    var article = db.Post.Find(id);
    article.LastUpdate = DateTime.Now;
    article.ChapterCount = counter;

    db.Entry(article).State = EntityState.Modified;
    db.SaveChanges();
    }


    How i can solve this ?










    share|improve this question


























      up vote
      3
      down vote

      favorite









      up vote
      3
      down vote

      favorite











      In my Controller I execute another Void Function after the date saved to DB. But sometimes it's show this error :




      A second operation started on this context before a previous
      asynchronous operation completed. Use 'await' to ensure that any
      asynchronous operations have completed before calling another method
      on this context. Any instance members are not guaranteed to be thread
      safe.




      ...and here is a sample of my controller :



      public ActionResult All(Chapter chapter){

      var x = db.Post.Where(p => p.PostID == chapter.PostID).FirstOrDefault();
      if (x == null){return View(chapter);}

      counter++;

      db.Chapter.Add(chapter);
      db.SaveChangesAsync();

      savepost(chapter.PostID, counter);

      return RedirectToAction("Index");
      }


      and here is the Void method:



      public void savepost(int id,int counter)
      {
      var article = db.Post.Find(id);
      article.LastUpdate = DateTime.Now;
      article.ChapterCount = counter;

      db.Entry(article).State = EntityState.Modified;
      db.SaveChanges();
      }


      How i can solve this ?










      share|improve this question















      In my Controller I execute another Void Function after the date saved to DB. But sometimes it's show this error :




      A second operation started on this context before a previous
      asynchronous operation completed. Use 'await' to ensure that any
      asynchronous operations have completed before calling another method
      on this context. Any instance members are not guaranteed to be thread
      safe.




      ...and here is a sample of my controller :



      public ActionResult All(Chapter chapter){

      var x = db.Post.Where(p => p.PostID == chapter.PostID).FirstOrDefault();
      if (x == null){return View(chapter);}

      counter++;

      db.Chapter.Add(chapter);
      db.SaveChangesAsync();

      savepost(chapter.PostID, counter);

      return RedirectToAction("Index");
      }


      and here is the Void method:



      public void savepost(int id,int counter)
      {
      var article = db.Post.Find(id);
      article.LastUpdate = DateTime.Now;
      article.ChapterCount = counter;

      db.Entry(article).State = EntityState.Modified;
      db.SaveChanges();
      }


      How i can solve this ?







      c# asp.net entity-framework






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 4 at 8:28









      Prisoner ZERO

      7,0751267106




      7,0751267106










      asked Nov 4 at 8:09









      Dummies EBooks

      305




      305
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          4
          down vote



          accepted










          Shortest fix:



          //db.SaveChangesAsync(); 
          db.SaveChanges();


          the slightly better option:



          public async Task<ActionResult> All(Chapter chapter)
          {
          ....
          await db.SaveChangesAsync();
          ...
          }


          You are not awaiting the call to SaveChangesAsync(), meaning it will (can) be forked off on a separate thread. And then giving you this error.



          As an exercise, you can make a similar change to the SavePost() method:




          • make it an async Task method

          • replace SaveChanges() with await db.SaveChangesAsync()

          • await the call to SavePost()






          share|improve this answer























          • Got this problem The property 'ChapterID' is part of the object's key information and cannot be modified.
            – Dummies EBooks
            Nov 4 at 8:30






          • 1




            Which is totally unrelated, ask another question - and provide the relevant code there.
            – Henk Holterman
            Nov 4 at 8:33










          • As a solution it works but in my controller i add multiple model to database using foreach, because the table id of Chapter is identity and given by model i got this problem .. Do you have idea how i can add multi model using for each and the important thing to get the next Id In DB since it's primary key
            – Dummies EBooks
            Nov 4 at 8:40










          • Well after i Left the action result as i posted and i take you advice about change the void to async task and the changed there as well the db.save to SaveChangesAsync It's works and no problem .. Thanks for all and Well Done
            – Dummies EBooks
            Nov 4 at 8:43










          • When you make SavePost async you have to await it, you can't do that with your original non-task All action ...
            – Henk Holterman
            Nov 4 at 9:57













          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',
          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%2f53138888%2fa-second-operation-started-on-this-context%23new-answer', 'question_page');
          }
          );

          Post as a guest
































          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          4
          down vote



          accepted










          Shortest fix:



          //db.SaveChangesAsync(); 
          db.SaveChanges();


          the slightly better option:



          public async Task<ActionResult> All(Chapter chapter)
          {
          ....
          await db.SaveChangesAsync();
          ...
          }


          You are not awaiting the call to SaveChangesAsync(), meaning it will (can) be forked off on a separate thread. And then giving you this error.



          As an exercise, you can make a similar change to the SavePost() method:




          • make it an async Task method

          • replace SaveChanges() with await db.SaveChangesAsync()

          • await the call to SavePost()






          share|improve this answer























          • Got this problem The property 'ChapterID' is part of the object's key information and cannot be modified.
            – Dummies EBooks
            Nov 4 at 8:30






          • 1




            Which is totally unrelated, ask another question - and provide the relevant code there.
            – Henk Holterman
            Nov 4 at 8:33










          • As a solution it works but in my controller i add multiple model to database using foreach, because the table id of Chapter is identity and given by model i got this problem .. Do you have idea how i can add multi model using for each and the important thing to get the next Id In DB since it's primary key
            – Dummies EBooks
            Nov 4 at 8:40










          • Well after i Left the action result as i posted and i take you advice about change the void to async task and the changed there as well the db.save to SaveChangesAsync It's works and no problem .. Thanks for all and Well Done
            – Dummies EBooks
            Nov 4 at 8:43










          • When you make SavePost async you have to await it, you can't do that with your original non-task All action ...
            – Henk Holterman
            Nov 4 at 9:57

















          up vote
          4
          down vote



          accepted










          Shortest fix:



          //db.SaveChangesAsync(); 
          db.SaveChanges();


          the slightly better option:



          public async Task<ActionResult> All(Chapter chapter)
          {
          ....
          await db.SaveChangesAsync();
          ...
          }


          You are not awaiting the call to SaveChangesAsync(), meaning it will (can) be forked off on a separate thread. And then giving you this error.



          As an exercise, you can make a similar change to the SavePost() method:




          • make it an async Task method

          • replace SaveChanges() with await db.SaveChangesAsync()

          • await the call to SavePost()






          share|improve this answer























          • Got this problem The property 'ChapterID' is part of the object's key information and cannot be modified.
            – Dummies EBooks
            Nov 4 at 8:30






          • 1




            Which is totally unrelated, ask another question - and provide the relevant code there.
            – Henk Holterman
            Nov 4 at 8:33










          • As a solution it works but in my controller i add multiple model to database using foreach, because the table id of Chapter is identity and given by model i got this problem .. Do you have idea how i can add multi model using for each and the important thing to get the next Id In DB since it's primary key
            – Dummies EBooks
            Nov 4 at 8:40










          • Well after i Left the action result as i posted and i take you advice about change the void to async task and the changed there as well the db.save to SaveChangesAsync It's works and no problem .. Thanks for all and Well Done
            – Dummies EBooks
            Nov 4 at 8:43










          • When you make SavePost async you have to await it, you can't do that with your original non-task All action ...
            – Henk Holterman
            Nov 4 at 9:57















          up vote
          4
          down vote



          accepted







          up vote
          4
          down vote



          accepted






          Shortest fix:



          //db.SaveChangesAsync(); 
          db.SaveChanges();


          the slightly better option:



          public async Task<ActionResult> All(Chapter chapter)
          {
          ....
          await db.SaveChangesAsync();
          ...
          }


          You are not awaiting the call to SaveChangesAsync(), meaning it will (can) be forked off on a separate thread. And then giving you this error.



          As an exercise, you can make a similar change to the SavePost() method:




          • make it an async Task method

          • replace SaveChanges() with await db.SaveChangesAsync()

          • await the call to SavePost()






          share|improve this answer














          Shortest fix:



          //db.SaveChangesAsync(); 
          db.SaveChanges();


          the slightly better option:



          public async Task<ActionResult> All(Chapter chapter)
          {
          ....
          await db.SaveChangesAsync();
          ...
          }


          You are not awaiting the call to SaveChangesAsync(), meaning it will (can) be forked off on a separate thread. And then giving you this error.



          As an exercise, you can make a similar change to the SavePost() method:




          • make it an async Task method

          • replace SaveChanges() with await db.SaveChangesAsync()

          • await the call to SavePost()







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 4 at 9:57

























          answered Nov 4 at 8:19









          Henk Holterman

          206k22222393




          206k22222393












          • Got this problem The property 'ChapterID' is part of the object's key information and cannot be modified.
            – Dummies EBooks
            Nov 4 at 8:30






          • 1




            Which is totally unrelated, ask another question - and provide the relevant code there.
            – Henk Holterman
            Nov 4 at 8:33










          • As a solution it works but in my controller i add multiple model to database using foreach, because the table id of Chapter is identity and given by model i got this problem .. Do you have idea how i can add multi model using for each and the important thing to get the next Id In DB since it's primary key
            – Dummies EBooks
            Nov 4 at 8:40










          • Well after i Left the action result as i posted and i take you advice about change the void to async task and the changed there as well the db.save to SaveChangesAsync It's works and no problem .. Thanks for all and Well Done
            – Dummies EBooks
            Nov 4 at 8:43










          • When you make SavePost async you have to await it, you can't do that with your original non-task All action ...
            – Henk Holterman
            Nov 4 at 9:57




















          • Got this problem The property 'ChapterID' is part of the object's key information and cannot be modified.
            – Dummies EBooks
            Nov 4 at 8:30






          • 1




            Which is totally unrelated, ask another question - and provide the relevant code there.
            – Henk Holterman
            Nov 4 at 8:33










          • As a solution it works but in my controller i add multiple model to database using foreach, because the table id of Chapter is identity and given by model i got this problem .. Do you have idea how i can add multi model using for each and the important thing to get the next Id In DB since it's primary key
            – Dummies EBooks
            Nov 4 at 8:40










          • Well after i Left the action result as i posted and i take you advice about change the void to async task and the changed there as well the db.save to SaveChangesAsync It's works and no problem .. Thanks for all and Well Done
            – Dummies EBooks
            Nov 4 at 8:43










          • When you make SavePost async you have to await it, you can't do that with your original non-task All action ...
            – Henk Holterman
            Nov 4 at 9:57


















          Got this problem The property 'ChapterID' is part of the object's key information and cannot be modified.
          – Dummies EBooks
          Nov 4 at 8:30




          Got this problem The property 'ChapterID' is part of the object's key information and cannot be modified.
          – Dummies EBooks
          Nov 4 at 8:30




          1




          1




          Which is totally unrelated, ask another question - and provide the relevant code there.
          – Henk Holterman
          Nov 4 at 8:33




          Which is totally unrelated, ask another question - and provide the relevant code there.
          – Henk Holterman
          Nov 4 at 8:33












          As a solution it works but in my controller i add multiple model to database using foreach, because the table id of Chapter is identity and given by model i got this problem .. Do you have idea how i can add multi model using for each and the important thing to get the next Id In DB since it's primary key
          – Dummies EBooks
          Nov 4 at 8:40




          As a solution it works but in my controller i add multiple model to database using foreach, because the table id of Chapter is identity and given by model i got this problem .. Do you have idea how i can add multi model using for each and the important thing to get the next Id In DB since it's primary key
          – Dummies EBooks
          Nov 4 at 8:40












          Well after i Left the action result as i posted and i take you advice about change the void to async task and the changed there as well the db.save to SaveChangesAsync It's works and no problem .. Thanks for all and Well Done
          – Dummies EBooks
          Nov 4 at 8:43




          Well after i Left the action result as i posted and i take you advice about change the void to async task and the changed there as well the db.save to SaveChangesAsync It's works and no problem .. Thanks for all and Well Done
          – Dummies EBooks
          Nov 4 at 8:43












          When you make SavePost async you have to await it, you can't do that with your original non-task All action ...
          – Henk Holterman
          Nov 4 at 9:57






          When you make SavePost async you have to await it, you can't do that with your original non-task All action ...
          – Henk Holterman
          Nov 4 at 9:57




















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53138888%2fa-second-operation-started-on-this-context%23new-answer', 'question_page');
          }
          );

          Post as a guest




















































































          這個網誌中的熱門文章

          Tangent Lines Diagram Along Smooth Curve

          Yusuf al-Mu'taman ibn Hud

          Zucchini