开发者

Update model child collection in MVC 3 application?

This is part of a larger problem which has plagued me for a while now (see "EntityCollection already initialized" error with entity as model in Asp.Net MVC? for the entire picture).

But I found a web site with someone who had faced a similar problem and apparently solved it for his needs (see http://codeblog.shawson.co.uk/creating-an-order-order-details-style-form-using-asp-net-mvc2-entity-framework/ ). I tried it, but had to make some modifications to fit my code, and the helper methods supplied by a tutorial by Steven Sanderson (see previous post).

I'm very close it seems, but not quite:

        UpdateModel(consultant, "Consultant");

        if (vm.Programs != null) //Unnecessary? Can it even be null if it's initialized from the model?
            for (int i = 0; i < vm.Programs.Count; i++)
            {
                Program formProgram = vm.Programs[i];
                Program modelProgram = consultant.Programs.SingleOrDefault(x => x.Id == formProgram.Id);
                if (modelProgram == null)
                    _repository.AddPro开发者_开发知识库gram(formProgram);
                else
                    modelProgram = formProgram;
                UpdateModel(modelProgram); //Doesn't work. The modelProgram object does get updated with the correct property values, but it isn't saved to the repository...
            }
        _repository.Save();

Although this follows the example on the site above, and the modelProgram does get updated with the changed properties, these values are not saved to the database on _repository.Save() on the Consultant object, even though the modelProgram object is a reference to a Program object on the Consultant... What am I doing wrong?

I am using the Entity Framework by the way, if it isn't clear.

(BTW, if anyone has any input on the previous question and the whole picture, that would be welcome too, it is still unresolved).

Please help, I'm losing faith in MVC, which I so recently was so excited about...

UPDATE: There was apparently a mistake in here: UpdateModel didn't actually do any updating, I had just referenced a different object (the one in the viewmodel) for the modelProgram, so of course it had the right property values. I still want ideas for how to achieve this though...


Try moving the _repository.Save() inside the for loop.

Is your inner if correct? You are running UpdateModel(null) when modelProgram is null. This could crash and explain why nothing is getting saved.

Edit

Try putting in {}

            if (modelProgram == null)
               {
                 _repository.AddProgram(formProgram);
               }
            else                    
              {
                modelProgram = formProgram;                
                UpdateModel(modelProgram); 
               }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜