【发布时间】:2016-11-17 00:29:02
【问题描述】:
我是 Entity Framework 的新手,当一种方法调用另一种方法时,我对处置我的 DbContext 的正确方法感到困惑。这两个都被独立调用,这就是 DeleteSheet 是独立的原因。但是,当父(链)被删除时,DeleteChain 调用 DeleteSheet 来删除子。
我尝试在每种方法中处理,但是当我运行 DeleteChain 时,我得到:
The operation cannot be completed because the DbContext has been disposed.
开
db.Chains.Remove(chain);
我猜是因为我在删除子项时在 DeleteSheet 中处理了它。
这是我的方法:
public class ControllerHelper
{
private UranusContext db = new UranusContext();
public void DeleteChain(int? chainId)
{
var chain = db.Chains.Include(c => c.Sheets)
.SingleOrDefault(c => c.ChainId == chainId);
// Removes sheets (children)
foreach (var sheet in chain.Sheets.ToList())
{
DeleteSheet(sheet.SheetId);
}
db.Chains.Remove(chain);
db.SaveChanges();
db.Dispose();
}
public void DeleteSheet(int? sheetId)
{
var sheet = db.Sheets.Include(s => s.FileDetails)
.Include(s => s.SheetsCounties)
.SingleOrDefault(s => s.SheetId == sheetId);
foreach (var fileDetails in sheet.FileDetails.ToList())
{
db.FileDetails.Remove(fileDetails);
}
foreach (var sheetsCounties in sheet.SheetsCounties.ToList())
{
db.SheetsCounties.Remove(sheetsCounties);
}
db.Sheets.Remove(sheet);
db.SaveChanges();
db.Dispose();
}
}
在这种情况下如何正确处理 DbContext?我很困惑,因为如果我只在 DeleteChain 中处理,然后在 DeleteChain 之外调用 DeleteSheet,它就不会处理。
编辑:尝试 #2。我将每个包装在使用中并单独处理它们。但是,当我删除 DeleteSheet 中的孩子时,DeleteChain 并没有意识到我这样做并抛出:The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted. on db.SaveChanges() in DeleteChain。
尝试 #2。
public void DeleteChain(int? chainId)
{
using (UranusContext db = new UranusContext())
{
var chain = db.Chains.Include(c => c.Sheets)
.SingleOrDefault(c => c.ChainId == chainId);
// Removes sheets (children)
foreach (var sheet in chain.Sheets.ToList())
{
DeleteSheet(sheet.SheetId);
//db.Sheets.Remove(sheet);
}
db.Chains.Remove(chain);
db.SaveChanges();
}
}
public void DeleteSheet(int? sheetId)
{
using (UranusContext db = new UranusContext())
{
var sheet = db.Sheets.Include(s => s.FileDetails)
.Include(s => s.SheetsCounties)
.SingleOrDefault(s => s.SheetId == sheetId);
foreach (var fileDetails in sheet.FileDetails.ToList())
{
db.FileDetails.Remove(fileDetails);
}
foreach (var sheetsCounties in sheet.SheetsCounties.ToList())
{
db.SheetsCounties.Remove(sheetsCounties);
}
db.Sheets.Remove(sheet);
db.SaveChanges();
}
}
【问题讨论】:
标签: c# asp.net-mvc entity-framework