I know this was asked before, but after many hours of searching and coding, I canβt find a working and clean approach. Here is what I have:
public class QuestionModel { public int QuestionID { get; set; } public string QuestionText { get; set; } public IList<QuestionChoiceModel> Choices { get; set; } } public class QuestionChoiceModel { public int ChoiceID { get; set; } public string ChoiceText { get; set; } }
I am using EF 5 for this ASP.Net MVC application. A typical repository pattern and dependency injection using Ninject using InRequestScope() are in place and run smoothly. These models are mapped to / without objects.
Adding new questions to the database directly. I set the Question property for some QuestionChoice instances, and EF handles the rest.
The problem is in the updates. Suppose we have a question in a database with 3 QuestionChoices:
ChoiceID QuestionID ChoiceText -------- ---------- ---------- 1 1 blah blah 2 1 blah blah 3 1 blah blah
When the question editing page opens (GET: / questions / Edit / 1), I show these 3 options using foreach in Razor. I wrote jQuery code that adds or removes the required markup for input elements if the user wants. Thus, QuestionChoice with ID = 1 can be edited on the client, ID = 2 can be deleted, and a new ID = 4 can be added. The form data is attached to the QuestionModel perfectly when the user clicks the "Save" button (POST: / questions / Edit / 1). The model is correctly mapped to the question object. That's where the story begins!
Now the Question object has a QuestionChoices set, some of which are already in the database, some of which must be added to the database, and some of them must be deleted from the database.
I read a lot of posts like: Entity Framework does not save modified children
I can handle changes in such a dirty way. And also new entries:
this._context.Entry(choice).State = EntityState.Added;
But I'm looking for a more elegant way. And also process records that need to be deleted. Is there a good approach to handle the full insert / update / delete of child objects in this scenario using EF? Honestly, I expected more from EF.
c # asp.net-mvc entity-framework
Delphi.Boy Oct 14 '14 at 17:40 2014-10-14 17:40
source share