I know it has been asked before, but after long hours of searching and coding I can't get to 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'm using EF 5 for this ASP.Net MVC application. Generic Repository Pattern and Dependency Injection with Ninject using InRequestScope()
are in place and work smoothly. These models are mapped to/from entities without a problem.
Adding new Questions to database is straight forward. I set Question property of some QuestionChoice instances, and EF handles the rest.
The problem is about updates. Assume we have a Question in database with 3 QuestionChoices:
ChoiceID QuestionID ChoiceText
-------- ---------- ----------
1 1 blah blah
2 1 blah blah
3 1 blah blah
When edit page of a Question opens (GET: /Questions/Edit/1), I show these 3 choices using a foreach
in Razor. I've written some JQuery code that adds or deletes required markup for input elements if user wants to. So, the QuestionChoice with ID=1 might be edited on client, ID=2 might be deleted, and a new ID=4 might be added. The form data is bound back to a QuestionModel perfectly when user presses the Save button (POST: /Questions/Edit/1). The model is mapped to a Question entity correctly. That is where the story begins!
Now the Question entity has a collection of QuestionChoices some of which are already in database, some should be added to database, and some should be deleted from database.
I've read many posts like:
Entity Framework not saving modified children
I can handle edits in that dirty way. And also new records by:
this._context.Entry(choice).State = EntityState.Added;
But I'm looking for a more elegant way. And also handle records that should be deleted. Is there a good approach to handle complete insert/update/delete of child entities in this scenario using EF? Honestly, I expected more from EF.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…