c# - 如何解决“操作无法完成,因为 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);
问题是什么?我究竟做错了什么?
解决方案
推荐阅读
- google-maps-api-3 - Google Maps draggable overlay on touch screen
- r - Regular expressions for catching stats and saving them on the fly
- reactjs - How can I pass this state?
- css - 如何从 Material-UI 中删除 TextField 的下划线?
- r - How to replace 'character-space-number' with 'character-dash-number' in long strings?
- javascript - 提取数组的键 - 没有重复
- jupyter-notebook - Persistent plotly plots in jupyter notebooks
- android - Android Studio Layout: reduce size of padding around button label
- python - string function in Python to extract between two characters
- java - 如何在组件测试中动态排除spring boot配置类