Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm implementing asp.net core project. In my controller class, create method, At first I insert a record in table APIApplicantHistory as a log history and then I do some calculation to get a value and after that I return back to the create method and and create a new record and insert it into APIApplicant table. For doing that, I wrote some code like below:

My problem is, after running the application and create a new record in APIApplicant, the below error is shown to me:

An unhandled exception occurred while processing the request. InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.

I appreciate if any one tells me where do I make a mistake?

What I have tried:

namespace CSDDashboard.Controllers
 {
   public class ApiapplicantsController : Controller
{
    private readonly CSSDDashboardContext _context;

    public ApiapplicantsController(CSSDDashboardContext context)
    {
        _context = context;
    }

   public async Task<IActionResult> Create([Bind("Id,ApiRequestDate,ApiRequestNo,Apiid,ApplicantId,GateId,LastRequestStatus,NocRequestDate,NocRequestNo,Url,Description,IsDeleted")] Apiapplicant apiapplicant)
    {
        ApiApplicantDto dto = new ApiApplicantDto();

        if (ModelState.IsValid)
        {
            //   Apiapplicant myapiapplicant = _context.Apiapplicant.LastOrDefault<Apiapplicant>();
            Apiapplicant myapiapplicant = _context.Apiapplicant.ToArray().Last();
            int temp = myapiapplicant.Id + 1;
            int calcApiApplicantHistoryId = APIApplicantHistoryLog(temp);


            var api = _context.Api.Single(p => p.Id == apiapplicant.Apiid);
            var gate = _context.Gate.Single(p => p.Id == apiapplicant.GateId);
            var applicant = _context.Applicant.Single(p => p.ApplicantId == apiapplicant.ApplicantId);
            //var apiapplicanthistory = _context.ApiApplicantHistory.Single(p => p.Id == apiapplicant.LastRequestStatus);


            dto.apiId = api.Id;
            dto.gateId = gate.Id;
            dto.applicantId = applicant.ApplicantId;

            using (var _context = new CSSDDashboardContext())
            {

                _context.Set<Apiapplicant>().Add(new Apiapplicant
                {

                    Apiid = dto.apiId,
                    GateId = dto.gateId,
                    ApplicantId = dto.applicantId,
                    LastRequestStatus = calcApiApplicantHistoryId,


                    ApiRequestDate = apiapplicant.ApiRequestDate,
                    ApiRequestNo = apiapplicant.ApiRequestNo,
                    NocRequestDate = apiapplicant.NocRequestDate,
                    NocRequestNo = apiapplicant.NocRequestNo,
                    Url = apiapplicant.Url,
                    Description = apiapplicant.Description,
                    IsDeleted = false
                });
                 await _context.SaveChangesAsync();
             };

            return RedirectToAction(nameof(Index));
        }

        return View(apiapplicant);
    }


   private  int APIApplicantHistoryLog(int myAPIApplicantId)
    {
        APIApplicantHistoryDto mydto = new APIApplicantHistoryDto();

      //  var apiapplicantt = _context.ApiApplicantHistory.Single(p => p.ApiApplicantId == myAPIApplicantId);
     //   mydto.APIApplicantHistoryId = apiapplicantt.Id;

        using (var _context = new CSSDDashboardContext())
        //     using (var transaction = _context.Database.BeginTransaction())
        {

            _context.Set<ApiApplicantHistory>().Add(new ApiApplicantHistory
            {

                //   ApiApplicantId = mydto.APIApplicantHistoryId,
                ApiApplicantId = myAPIApplicantId,
                Date = null,
                SentResponseType = 0,
                UnconfirmedReason = 0,
                LastReqStatus = 0,
                Description = "",
                IdDeleted = false   // This field should be totally omited from SQL server
            }) ;
             _context.SaveChangesAsync();


            var myArrayList = new List<int>();

            var result = from x in _context.ApiApplicantHistory where x.ApiApplicantId == myAPIApplicantId
                         select new { x.Id };

            foreach (var i in result)
                myArrayList.Add(i.Id);

            return myArrayList.Max(); ;

        }
    }
   }
Posted
Updated 15-Feb-20 8:33am

1 solution

Your whole approach looks "confused".

You're passing a dbContext to your constructor and then create others in the body of your code.

dbContexts are "light" and fast to create, whose lifetime should be "short". "Passing them around" is pointless and probably conflicting with the code in your methods.
 
Share this answer
 
Comments
ElenaRez 16-Feb-20 0:22am    
Thank you for the reply. Is it possible that the problem is due to not using async and await for the method
APIApplicantHistoryLog
?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900