MVC Updatemodel and Linq-To-Sql create a new entity instead of updating

I have a survey form with the following data hierarchy

survey - surveyQuestions - surveyQuestionOptions

I use updateModel to update the Survey object in my save method, which is great for polling and pollingQuestions, however surveyQuestionOptions appear updated when I check the updateSurvey variable in the debugger, but after I call SubmitChanges, I get new surveyQuestionOption entries instead of updates. My code is as follows

HTML

<%= Html.TextBox("Survey.Id", Model.Id)%> <%= Html.TextBox("Survey.SurveyName", Model. SurveyName)%> <%= Html.TextBox("Survey.SurveyQuestions[0].Id", Model.Id)%> <%= Html.TextBox("Survey.SurveyQuestions[0].Question", Model. Question)%> <%= Html.TextBox("Survey.SurveyQuestions[0].SurveyQuestionOptions[0].Id", Model.Id)%> <%= Html.TextBox("Survey.SurveyQuestions[0].SurveyQuestionOptions[0].Option", Model. Option)%> 

controller

 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Save(int? id, IList<ChannelForm> channelForms, FormCollection fc) { Survey updateSurvey = new Survey(); //if this is an existing Surveyretrieve that record from the database ready for updating if (id != 0) { updateSurvey = surveynRepository.GetSingle(Convert.ToInt32(id)); } try { // updateSurvey and all child elements UpdateModel(updateSurvey, "Survey"); surveyRepository.Save(); return View(); }catch {return View();} } 

Any help is appreciated

+4
source share
3 answers
  Survey updateSurvey; if (id == 0) { updateSurvey = new Survey(); } else { updateSurvey = surveyRepository.GetSingle(Convert.ToInt32(id)); } try { ..etc 
0
source

Mmm ... I did not try to update the child directly, for example, using complex models (different depth levels). I mainly use ViewModel and then use ViewModel to update the actual model (LinqtoSQL classes).

I would update the child file like this:

Get current saved poll

 currentSurvey = surveyRepository.GetSingle(Convert.ToInt32(id)); foreach (var option in updateSurveyViewModel.SurveyQuestions) { //check if exist var current = currentSurvey.SingleOrDefault(a=> a.Id == option.Id); if (current == null) { //Create a NewOne and attach it to the curentSurvey } else { //already exist, Update the option current.Option = option.Option; //... } } 

I know that this is not the level of depth of the problem, but the same concept.

0
source

I tried with LoadOptions in LINQ to SQL:

 var loadOptions = new System.Data.Linq.DataLoadOptions(); loadOptions.LoadWith<Contact>(c => c.ContactEmails); db.LoadOptions = loadOptions; Contact old = db.Contacts.SingleOrDefault(c => c.ContactID == id); UpdateModel(old, "Contact"); db.SubmitChanges(); 

Did not help. All existing ContactEmail are deleted and reinserted.

0
source

All Articles