Ошибка структуры сущности: невозможно получить доступ к удаленному объекту - PullRequest
0 голосов
/ 05 ноября 2019

В моем методе ниже, который написан с использованием c # в ядре asp.net, я получаю ошибку при выполнении любого из приведенных ниже операторов обновления. В чем проблема с использованием await SaveContextAsync ();Я заметил, что я не получаю сообщение об ошибке при использовании только SaveContext ();

Я получаю следующую ошибку:

 Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection 
 and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() 
 on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency 
 injection container take care of disposing context instances.
 Object name: 'FXDB1Context'.

Я не уверен, почему я получаю эту ошибку.

 public async Task<IdentityResult> ApproveUserChangeRequest(UserChangeRequest userChangeRequest, string approvedByAuthUserName, string authApplicationName)
    {
        var userChangeRequestRepository = UserChangeRequestRepository.GetAllAsList();
        var userChangeRequestApprovalRepository = UserChangeRequestApprovalRepository.GetAllAsList();
        var appSettingRepository = AppSettingRepository.GetAllAsList();
        var clientCompanyContactRepository = ClientCompanyContactRepository.GetAllAsList();
        var applicationUserRepo = ApplicationUserRepo.GetAllAsList();
        int approvedByAuthUserID = GetApprovedByUserId(authApplicationName, approvedByAuthUserName);

        // Check if UserChangeRequest is still Pending
        bool isUserChangeRequestPending = userChangeRequestRepository.Any(x => x.Id == userChangeRequest.Id && x.ChangeStatus == "Pending");

        if (isUserChangeRequestPending && approvedByAuthUserID > 0)
        {
            // Inserting record in the UserChangeRequestApproval table
            InsertUserChangeRequestApproval(userChangeRequest);
            await SaveContextAsync();

            using (var userTransaction = Context.Database.BeginTransaction())
            {
                using (var securityTransaction = _securityContext.Database.BeginTransaction())
                {
                    try
                    {
                        //Get the Number of approval required for Internal and External Users
                        int? internalApprovalsRequired = GetApprovals("InternalUserChangeRequestApprovalsRequired", appSettingRepository);
                        int? externalApprovalsRequired = GetApprovals("ExternalUserChangeRequestApprovalsRequired", appSettingRepository);

                        //Get the name of the application the auth user belongs to
                        var authUserApplicationName = GetApplicationName(userChangeRequest.AuthUserId);

                        //Get the Number of approvals for the request
                        var numberOfAprovals = userChangeRequestApprovalRepository.Where(x => x.UserChangeRequestId == userChangeRequest.Id).Count();

                        //If the number of approvals is equal or greater than the Approvals required then Update AppUser or Contact details
                        if ((authUserApplicationName == "ArgentexTrader" && numberOfAprovals >= internalApprovalsRequired) || (authUserApplicationName == "ArgentexClient" && numberOfAprovals >= externalApprovalsRequired))
                        {
                            //Updating the clientcontact table
                            UpdateClientContact(userChangeRequest, clientCompanyContactRepository);


                            //Updating the auth user table
                            UpdateAuthUser(userChangeRequest);


                            //Updating the IdentityDB user table
                            UpdateIdentityDBUser(userChangeRequest, applicationUserRepo);

                            //Updating the UserChangeRequest table
                            userChangeRequest.ChangeStatus = "Approved";
                            UserChangeRequestRepository.Update(userChangeRequest);

                            await SaveContextAsync();
                            userTransaction.Commit();
                            securityTransaction.Commit();
                            return IdentityResult.Success;
                        }

                    }
                    catch (Exception ex)
                    {
                        userTransaction.Rollback();
                        securityTransaction.Rollback();
                        _logger.Error(ex);
                        return IdentityResult.Failed(new IdentityError { Description = ex.Message });
                    }
                }
            }
        }
        return null;
    }

1 Ответ

0 голосов
/ 06 ноября 2019

Ошибка говорит о том, что разрешенный контекст пытается сделать Одноразовым .

Для получения дополнительной информации: Использование операторовв C #

using оператор является процессом только для области, поэтому эта ошибка означает, что ваша программа пытается использовать такие же экземпляры "context" в другом месте, что она не может использовать, потому что какЯ упоминал, что это процесс "только для сферы".

В вашем примере:

using (var userTransaction = Context.Database.BeginTransaction())
{
   using (var securityTransaction = _securityContext.Database.BeginTransaction())
   {
   }
}

Вы можете сделать это просто и не использовать область действия using, или вы можете быть уверены, что контекст используется только в этих using областях.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...