[英]Strange DB-context behaviour when updating collection (Works when stepping through the code in debugger)
I have a really strange behavior that actually gives me different result if I step through the code using the debugger or just run the app (press play). 我有一个非常奇怪的行为,如果我使用调试器逐步执行代码或只是运行应用程序(按播放),实际上会给我不同的结果。
The model looks like this; 该模型如下所示;
public class QuestionPack
{
public int QuestionPackID { get; set; }
public string Hashcode { get; set; }
public virtual ICollection<Question> Questions { get; set; }
}
And I save this class to the DB using a repository-pattern like this; 然后使用类似的存储库模式将此类保存到数据库;
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();
}
}
This works perfectly when adding data, but when I try to update (the else statement) I get doubles on the Questions, eg. 这在添加数据时非常有效,但是当我尝试更新(else语句)时,我在问题上会翻倍。 the questions get saved but with the already saved questions so if i have 4 questions, update that question with ONE question and save, i will end up with 9 questions. 问题已保存,但已保存的问题已保存,因此如果我有4个问题,请用一个问题更新该问题并保存,最后我将得到9个问题。
BUT; 但; if I step through the code using the debugger (start from the SaveQuestionPack-function and hit "continue", after context.saveChanges()" I get the expected result. I'm so confused I don't even know where to start looking. I guess it have something to do with the fact that I'm trying to store a collection, but why does it work when I step through the save process? 如果我使用调试器逐步执行代码(从SaveQuestionPack函数开始,然后单击“ continue”,则在context.saveChanges()之后,我会得到预期的结果。我很困惑,我什至不知道从哪里开始寻找我想这与我要存储集合的事实有关,但是当我逐步执行保存过程时为什么它起作用?
Any input is appreciated. 任何输入表示赞赏。
I think i solved it but im not really sure why it works... 我想我已经解决了,但我不确定是为什么...
I added this; 我添加了这个;
dbEntry.Questions.Clear();
before; 之前;
dbEntry.Questions = questionpack.Questions;
Anyone having a idea why this corrected the fault? 有人知道为什么这可以纠正错误吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.