Correct way to update a Model from a Viewmodel

Asked

Viewed 217 times

2

I have the following question: do I get one Viewmodel in the Controller of ASP.NET. In the update method I have two options:

  • 1st option : transfer the Viewmodel to the respective bank entity directly and update.
  • 2nd option : First search for the id of the object to be updated and then transfer the Viewmodel to the respective bank entity and update.

What would be the right way to do it?

  • face, take a look at these links http://eduardopires.net.br/2013/asp-net-mvc-view-model-pattern-quando-e-como-utilizar/ http://eduardopires.net.br/2013/08/asp-net-mvc-utilizando-automapper-comview-model-pattern/ http://www.asp.net/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-3 http://www.princiweb.com.br/blog/programacao/design-patterns/o-que-e-e-e-como-utilizar-o-padrao-view-modelem-um-projeto-aspnet-mvc.html

  • The first option would be to create a table in the database with the Viewmodel data?

1 answer

3

Depends on the bank’s technology.

Using Entity Framework

Option 1 is better. When mapping your Viewmodel for a Model and mark the entry for change, the Entity Framework checks whether this entity, with the primary key provided, exists. If it exists, by commanding the SaveChanges of the context, the entity is updated.

Since the Entity Framework gives you everything, option 2 is unnecessary.

Using another method

This is the case if you search for the entity in the bank, change it and save it (method 2), unless this other method is an ORM that does this work for you.

  • 1

    Thanks Gypsy was a doubt I had to end it today haha.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.