我是新來的實體框架,我很困惑正確的方式來處置我的DbContext當一個方法調用另一個。這些都是獨立調用的,這就是爲什麼DeleteSheet是分開的。但是,刪除父項(鏈)時,DeleteChain調用DeleteSheet刪除子項。正確的方式來處置DbContext時,一個方法調用另一個,都使用DbContext
我嘗試各種方法來處理,但是當我運行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.
在db.SaveChanges()
,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();
}
}
這似乎是最可行和有效的。我只有一個問題:當你傳遞UranusContext數據庫時,是不是創建了一個UranusContext的新實例?是處置還是增加了不必要的開銷? – justiceorjustus
不,當您傳遞對上下文的引用時 - 不會創建任何內容(並且根本沒有開銷)。 – Evk