2015-11-23 66 views
1

我編寫了用新安全密碼問題更新我的表(SecurityQuestionAnswer)的代碼,並將舊問題轉移到另一個表(SecurityQuestionAnswersArchives)。安全問題總數爲3.我能夠更新當前表,但是當我將相同的行添加到歷史記錄表時,它會顯示奇怪的數據:只添加兩條記錄而不是3條,並且數據也被複制。我的代碼如下:無法在Entity Framework中的存檔表中添加數據

if (oldQuestions.Any()) 
     { 
      var oldquestionstoarchivelist = new List<SecurityQuestionAnswersArchives>(); 
      var oldquestionstoarchive =new SecurityQuestionAnswersArchives(); 
      for (int i = 0; i < 3; i++) 
      { 
       oldquestionstoarchive.Id = oldQuestions[i].Id; 
       oldquestionstoarchive.SecurityQuestionId = oldQuestions[i].SecurityQuestionId; 
       oldquestionstoarchive.Answer = oldQuestions[i].Answer; 
       oldquestionstoarchive.UpdateDate = oldQuestions[i].UpdateDate; 
       oldquestionstoarchive.IpAddress = oldQuestions[i].IpAddress; 
       oldquestionstoarchive.SecurityQuestion = oldQuestions[i].SecurityQuestion; 
       oldquestionstoarchive.User = oldQuestions[i].User; 
       oldquestionstoarchivelist.Add(oldquestionstoarchive); 
      } 
      user.SecurityQuestionAnswersArchives = oldquestionstoarchivelist; 
      //await Store.UpdateAsync(user); 
      _dbContext.ArchiveSecurityQuestionAnswers.AddRange(oldquestionstoarchivelist); 
      _dbContext.SecurityQuestionAnswers.RemoveRange(oldQuestions); 
      await _dbContext.SaveChangesAsync(); 
      oldquestionstoarchivelist.Clear(); 

     } 

更新1

循環看起來不錯,它重複三次(0,1,2),預計。第一個問題與AddRange功能,我通過一個列表,但它需要IEnumerable輸入,我糾正它使用下面的代碼。

IEnumerable<SecurityQuestionAnswersArchives> finalArchiveses = oldquestionstoarchivelist; 
_dbContext.ArchiveSecurityQuestionAnswers.AddRange(finalArchiveses); 

另一個問題是重複的數據,我無法弄清楚問題出在哪裏。請幫我找出答案。

非常感謝您的幫助!

回答

0

Got it!只是在任何人有同樣問題的情況下共享。 問題是在錯誤的地方初始化。我移動了 var oldquestionstoarchive = new SecurityQuestionAnswersArchives(); 在Forloop中,現在變量將在每次迭代中保持唯一值。

var oldquestionstoarchivelist = new List<SecurityQuestionAnswersArchives>(); 
      for (int i = 0; i < 3; i++) 
      { 
       var oldquestionstoarchive = new SecurityQuestionAnswersArchives(); 
       oldquestionstoarchive.SecurityQuestionId = oldQuestions[i].SecurityQuestionId; 
       oldquestionstoarchive.Answer = oldQuestions[i].Answer; 
       oldquestionstoarchive.UpdateDate = oldQuestions[i].UpdateDate; 
       oldquestionstoarchive.IpAddress = oldQuestions[i].IpAddress; 
       oldquestionstoarchive.SecurityQuestion = oldQuestions[i].SecurityQuestion; 
       oldquestionstoarchive.User = oldQuestions[i].User; 
       oldquestionstoarchivelist.Add(oldquestionstoarchive); 
      } 
相關問題