Correct way to update a Model from a ViewModel

2

I have the following question: Do I get a ViewModel in the Controller of ASP.NET. In the upgrade method I have two options:

  • 1st option: transfer the ViewModel to the respective bank entity directly and update.
  • 2nd option: Search first for the id of the object to be updated and then transfer the ViewModel to the respective entity of the database and update.

What would be the right way to do it?

    
asked by anonymous 17.06.2016 / 19:53

1 answer

3

Depends on the technology of the bank.

Using Entity Framework

Option 1 is best. When you map your ViewModel to a Model and mark the entry for change, the Entity Framework checks to see if this entity exists with the given primary key. If it exists, when you control the SaveChanges of the context, the entity is updated.

As the Entity Framework confers everything to you, option 2 is unnecessary.

Using another method

That's where you get 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.

    
17.06.2016 / 19:59