[英]Strange DB-context behaviour when updating collection (Works when stepping through the code in debugger)
我有一個非常奇怪的行為,如果我使用調試器逐步執行代碼或只是運行應用程序(按播放),實際上會給我不同的結果。
該模型如下所示;
public class QuestionPack
{
public int QuestionPackID { get; set; }
public string Hashcode { get; set; }
public virtual ICollection<Question> Questions { get; set; }
}
然后使用類似的存儲庫模式將此類保存到數據庫;
public class EFQuestionPackRepository : IQuestionPackRepository
{
private EFDbContext context = new EFDbContext();
public IQueryable<QuestionPack> QuestionsPacks
{
get { return context.QuestionPacks; }
}
public void SaveQuestionPack(QuestionPack questionpack)
{
if (questionpack.QuestionPackID == 0)
{
context.QuestionPacks.Add(questionpack);
}
else
{
QuestionPack dbEntry = context.QuestionPacks.Find(questionpack.QuestionPackID);
if (dbEntry != null)
{
dbEntry.Hashcode = questionpack.Hashcode;
dbEntry.Questions = questionpack.Questions;
}
}
context.SaveChanges();
}
}
這在添加數據時非常有效,但是當我嘗試更新(else語句)時,我在問題上會翻倍。 問題已保存,但已保存的問題已保存,因此如果我有4個問題,請用一個問題更新該問題並保存,最后我將得到9個問題。
但; 如果我使用調試器逐步執行代碼(從SaveQuestionPack函數開始,然后單擊“ continue”,則在context.saveChanges()之后,我會得到預期的結果。我很困惑,我什至不知道從哪里開始尋找我想這與我要存儲集合的事實有關,但是當我逐步執行保存過程時為什么它起作用?
任何輸入表示贊賞。
我想我已經解決了,但我不確定是為什么...
我添加了這個;
dbEntry.Questions.Clear();
之前;
dbEntry.Questions = questionpack.Questions;
有人知道為什么這可以糾正錯誤嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.