ObjectDisposedException во время Context.Entry().Reload()

303
31 августа 2017, 16:58

Добрый день!

Использую EF 6. Почему может возникать ObjectDisposedException во время Context.Entry().Reload()?

Сначала делается вызов Context.SaveChanges(true), а сразу за ним я пытаюсь перезагрузить информацию из БД с помощью Context.Entry(outDoc).Reload(). Иногда может возникать ObjectDisposedException в этот момент. Вызовы метода Dispose() между ними нет.

Подскажите пожалуйста, в чем может быть дело?

Исключение:

    System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
    at System.Data.Entity.Core.Objects.ObjectContext.ReleaseConnection()
    at System.Data.Entity.Core.Objects.ObjectContext.RefreshEntities(RefreshMode refreshMode, IEnumerable collection)
    at System.Data.Entity.Core.Objects.ObjectContext.Refresh(RefreshMode refreshMode, Object entity)
    at System.Data.Entity.Internal.InternalEntityEntry.Reload()
    at System.Data.Entity.Infrastructure.DbEntityEntry`1.Reload()
    at WCF_SupplierPortal.Controller.DBController._InsertOutgoingDocument(OutgoingDocument data)

Код:

namespace Controller
{
    public class DBController
    {
        #region  .ctor()
        public DBController()
        {
            Context = new LPTransitContext();
        }
        internal DBController(ILPTransitContext context)
        {
            Context = context;
        }
        /// <inheritdoc />
        ~DBController()
        {
            Context?.Dispose();
        }
        #endregion

        private static readonly object OutDocLocker = false;
        internal readonly ILPTransitContext Context;
        internal LPTransitModel.OutgoingDocument _InsertOutgoingDocument(InModel.OutgoingDocument data)
        {
            lock (OutDocLocker)
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions {IsolationLevel = System.Transactions.IsolationLevel.Serializable}))
                {
                    LPTransitModel.OutgoingDocument outDoc = new LPTransitModel.OutgoingDocument
                    {
                        OriginalDocumentNumber = data.OriginalDocumentNumber,
                        EdoInvoiceFileName = data.EdoInvoiceFileName,
                        EdoAuxiliaryFileName = data.EdoAuxiliaryFileName,
                        ...
                    };
                    LPTransitModel.OutgoingDocument dbOutgoingDocument;
                    try
                    {
                        dbOutgoingDocument = (from outDocument in Context.OutgoingDocument
                            where
                            ...
                            select outDocument).FirstOrDefault();
                        if (dbOutgoingDocument == null && ((ActionTypeEnum) data.ActionType == ActionTypeEnum.NewRecord || (ActionTypeEnum) data.ActionType == ActionTypeEnum.Update))
                        {
                            //Новая запись
                            outDoc.IsNew = true;
                            Context.OutgoingDocument.Add(outDoc);
                            Context.SaveChanges(true);
                            **Context.Entry(outDoc).Reload(); //PROBLEM HERE**
                            dbOutgoingDocument = outDoc;
                        }
                        else
                        {
                            //Удаление или обновление
                            if (dbOutgoingDocument == null) throw new ObjectNotFoundException($"No records to Delete");
                            outDoc.id = dbOutgoingDocument.id;
                            outDoc.IsNew = dbOutgoingDocument.IsNew;
                            outDoc.IsUpdate = dbOutgoingDocument.IsUpdate;
                            outDoc.IsDelete = dbOutgoingDocument.IsDelete;
                            outDoc.TransactionNum = dbOutgoingDocument.TransactionNum;
                            switch ((ActionTypeEnum) data.ActionType)
                            {
                                case ActionTypeEnum.NewRecord:
                                case ActionTypeEnum.Update:
                                    outDoc.IsUpdate = true;
                                    outDoc.IsDelete = false;
                                    Context.Entry(dbOutgoingDocument).CurrentValues.SetValues(outDoc);
                                    Context.SaveChanges(true);
                                    **Context.Entry(dbOutgoingDocument).Reload(); //PROBLEM HERE**
                                    break;
                                case ActionTypeEnum.Delete:
                                    dbOutgoingDocument.IsNew = false;
                                    dbOutgoingDocument.IsUpdate = false;
                                    dbOutgoingDocument.IsDelete = true;
                                    Context.SaveChanges(true);
                                    **Context.Entry(dbOutgoingDocument).Reload(); //PROBLEM HERE**
                                    break;
                                case ActionTypeEnum.DoNothing:
                                    break;
                                default:
                                    throw new ArgumentOutOfRangeException();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        HandleException(ex);
                        throw;
                    }
                    try
                    {
                        scope.Complete();
                    }
                    catch (Exception ex)
                    {
                        HandleException(ex);
                        throw;
                    }
                    return dbOutgoingDocument;
                }
        }
    }
}
READ ALSO
Почему в Task приходит неверный параметр?

Почему в Task приходит неверный параметр?

Начал изучать работу с Task в C#, тк

290
Одинарный вывод сообщения в цикле foreach - C#

Одинарный вывод сообщения в цикле foreach - C#

Есть некий код банкомата, где пользователю необходимо сначала ввести свой ид

364
Массив с ключами javascript

Массив с ключами javascript

Мне нужно сделать массив который хранит данные, знаю что можно сделать так

325
Возможно ли обращаться к woocommerce напрямую, без сервера и аутентификации?

Возможно ли обращаться к woocommerce напрямую, без сервера и аутентификации?

Здравствуйте, в woocommerce никак не могу найти способа работы с плагином без аутентификации (только get запросы нужны), возможно ли как-то напрямую...

336