首页 > 解决方案 > 如何解决“操作无法完成,因为 DbContext 已被释放。” 同时保存操作?

问题描述

我正在尝试将数据插入到与另一个表有关系的表中,该表又与另一个表相关。尝试将数据插入表时出现异常

操作无法完成,因为 DbContext 已被释放

代码:

    using (var transaction = _crmContext.Database.BeginTransaction())
    {
        try
           {
             if (primaryPersonContact.Id > 0)
                    {
                        _crmContext.Entry(primaryPersonContact).State = EntityState.Modified;
                        await _crmContext.SaveChangesAsync().ConfigureAwait(false);
                    }
                    else
                    {
                        customer.Person.Contact2 = _crmContext.Set<Contact>().Add(customer.Person.Contact2);
                        await _crmContext.SaveChangesAsync().ConfigureAwait(false);
                    }
if (primaryPersonContact.Id > 0)
                    {
                        _context.Entry(primaryPersonContact).State = EntityState.Modified;
                        //_crmContext.Entry(customer.Person.Contact2).State = EntityState.Modified;
                        await _crmContext.SaveChangesAsync().ConfigureAwait(false);
                    }
                    else
                    {
                        primaryPersonContact = _crmContext.Set<Contact>().Add(primaryPersonContact);
                        await _crmContext.SaveChangesAsync().ConfigureAwait(false);
                    }

                        if (primaryContactPerson.Id > 0)
                    {
                        _crmContext.Entry(primaryContactPerson).State = EntityState.Modified;
                        await _crmContext.SaveChangesAsync().ConfigureAwait(false);
                    }
                    else
                    {
                        primaryContactPerson.PrimaryContact = primaryPersonContact.Id;// to insert contact table Id to person Table.
                        primaryContactPerson = _crmContext.Set<Person>().Add(primaryContactPerson);
                        await _crmContext.SaveChangesAsync().ConfigureAwait(false);
                    }

                    if (customer.Id > 0)
                    {
                        _crmContext.Entry(customer).State = EntityState.Modified;
                        await _crmContext.SaveChangesAsync().ConfigureAwait(false);
                    }
                    else
                    {
                        customer.CustomerId = Guid.NewGuid();
                        customer.PrimaryContact = primaryContactPerson.Id; //To insert primary contact person Id to customer table.
                        customer = _crmContext.Set<Customer>().Add(customer);
                        await _crmContext.SaveChangesAsync().ConfigureAwait(false);
                    }
                    transaction.Commit();

错误发生在线路上

await _crmContext.SaveChangesAsync().ConfigureAwait(false);

问题是什么?我究竟做错了什么?

标签: c#winformsentity-frameworkdbcontext

解决方案


推荐阅读