开发者

How do i update a collection of objects with the entity framework?

开发者 https://www.devze.com 2023-03-28 17:26 出处:网络
I have two entities: Question and Multiple_Choice_Question. A Question object has a list of Multiple_Choice_Question开发者_JS百科 objects. To edit these objects, I pass the Question and the list of Mu

I have two entities: Question and Multiple_Choice_Question. A Question object has a list of Multiple_Choice_Question开发者_JS百科 objects. To edit these objects, I pass the Question and the list of Multiple_Choice_Question objects to a ViewModel that displays them on my asp.net website.

On [HttpPost], i get the question object from the DBContext and change the old properties with the new ones from the ViewModel. Then DBContext.SaveChanges(); updates.

To update the Multiple_Choice_Question list i do the following:

                foreach (MCQ newmcqq in model.MCQ)
            {
                Multiple_Choice_Question item = new Multiple_Choice_Question();
                item = db.Multiple_Choice_Question.First(x => x.mcq_id == newmcqq.mcq_id);
                item.mcq_id = newmcqq.mcq_id;
                item.choice_number = newmcqq.choice_number.ToString();
                item.choice_wording = newmcqq.choice_wording;
                item.help_text = newmcqq.help_text;
            }
db.SaveChanges();

Is there a better alternative?


Looping and updating individual items is the only way with LINQ. It really isn't intended for batch INSERT or UPDATE.

You're calling SaveChanges() outside the loop, so that's good. Still this is only scalable to a certain point. You'll eventually run into performance issues with it.

0

精彩评论

暂无评论...
验证码 换一张
取 消