简体   繁体   中英

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. 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.

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM