Categories
Development

How to solve the error A second operation started on this context before a previous operation completed

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:

 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));
        }
        ViewData["Apiid"] = new SelectList(_context.Api, "Id", "Name", apiapplicant.Apiid);
        ViewData["ApplicantId"] = new SelectList(_context.Applicant, "ApplicantId", "Name", apiapplicant.ApplicantId);
        ViewData["GateId"] = new SelectList(_context.Gate, "Id", "Name", apiapplicant.GateId);
        ViewData["sentResponseType"] = new SelectList(_context.EntityType.Where(g => g.EntityKey=="sentResponseType").ToList(), "ID", "name", apiapplicant.LastRequestStatusNavigation.SentResponseType);
        ViewData["unconfirmedReason"] = new SelectList(_context.EntityType.Where(g => g.EntityKey == "unconfirmedReason").ToList(), "Id", "name", apiapplicant.LastRequestStatusNavigation.UnconfirmedReason);
        ViewData["lastReqStatus"] = new SelectList(_context.EntityType.Where(g => g.EntityKey == "lastRequestStatus").ToList(), "Id", "name", apiapplicant.LastRequestStatusNavigation.LastReqStatus);
        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(); ;

        }
    }
   }

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?

Leave a Reply

Your email address will not be published. Required fields are marked *