2017-04-17 67 views
0

開發MVC 5應用程序。使用EF僅更新特定字段時遇到問題

查看:我有一個可編輯的表格。我只想更新已更改的行。另外,我只想更新2個字段,而不是全部。

這裏的視圖模型....

namespace SurveyingApp.ViewModels 
{ 
    [NotMapped] 
    public class SurveyResultsViewModel 
    { 
    // ------ hidden 
    public int EventId { get; set; } 

    [Display(Name = "Question")] 
    public string SurveyQuestionText { get; set; } 

    [Key] 
    public int Id { get; set; } // SurveyResults.Id 
    [Display(Name = "Answer")] 
    public string SelectedSurveyAnswer { get; set; } 

    public string Comments { get; set; } 
    } 
} 

這裏的更新/郵編...

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Index(
    [Bind(Include = "Id,SelectedSurveyAnswer,Comments")] 
     List<SurveyResultsViewModel> mySurveyResult) 
{ 
    if (ModelState.IsValid) 
    {  
    for (int i = 0; i < mySurveyResult.Count() - 1; i++) 
    { 

     SurveyResult surveyResult = new SurveyResult(); 
     //Attach the instance so that we don't need to load it from the DB 
     db.SurveyResults.Attach(surveyResult); 

     //Set the Id for my model. 
     surveyResult.Id = mySurveyResult[i].Id; 
     //update field from the VM 
     surveyResult.SurveyAnswer = mySurveyResult[i].SelectedSurveyAnswer; 
     surveyResult.Comments = mySurveyResult[i].Comments; 

     //Specify fields that should be updated. 
     db.Entry(surveyResult).Property(x => x.SurveyAnswer).IsModified = true; 
     db.Entry(surveyResult).Property(x => x.Comments).IsModified = true; 

     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 
    db.SaveChanges(); 
    return RedirectToAction("Index"); 
} 
return View(); 
} 

它的工作原理,直到第.IsModified statment(用於SurveyAnswer場)。錯誤是...

屬性'Id'是對象的關鍵信息的一部分,無法修改。

我不想更新Id字段。任何想法爲什麼會發生這種情況,或者我如何才能使其正常工作?

+0

我認爲Id是外鍵,它被設置爲自動增量,因此它會自動設置您不需要設置Id值的值。 – 2017-04-17 17:34:32

回答

2

我認爲這可能是您在附加對象之後將值賦給Id屬性的結果。在附加之前分配Id可能會產生更好的結果,但我沒有測試過。

無論如何,我會推薦一種不同的方法。如果我是你,我會做以下事情:

  • 遍歷列表。
  • 使用密鑰(大概是Id字段)從EF數據庫獲取對象
  • 更新您感興趣的兩個字段。
  • 保存循環完成時的更改。

我不知道你有多少條記錄。由於性能方面的原因,這樣做可能並不可行,但如果性能不是問題,那麼我會推薦這樣做。

+0

謝謝。你能提供一個簡單的例子嗎? – WebDevGuy2

+0

我把附件放下,放在我設置ID的地方,它起作用了!謝謝! – WebDevGuy2

+0

我很高興能夠提供幫助。抱歉,我錯過了你的第一個問題,忙碌的一天 – JuanR