A
A
Alexander2015-03-19 13:29:58
ASP.NET
Alexander, 2015-03-19 13:29:58

How to act in the following situation?

Good afternoon. I will briefly describe what the problem is.
Application on Asp.Net MVC 4 + EF. Let's say there is a domain model

class Model 
{
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }

        public string UserName { get; set; }
        public string Email { get; set; }
        public string PhoneNumber { get; set; }
}

and there is a view model ViewModel. It has everything the same as in the domain model, but for example, there is no PhoneNumber property.
You need to display the form with the ViewModel, edit it and make changes to the database.
How do I do.
1) I take from the Model database. I translate AutoMapper into a ViewModel and the controller sends this model to the view.
2) I edit some fields. submit and save the changes. But there is no PhoneNumber in the ViewModel. Those. I need to pull out the Model from the database, copy all the fields from the ViewModel to the Model (except for Id, PhoneNumber). Write to DB.
Question. And if there are a lot of fields in Model and ViewModel, is it possible to manually write a copy method from ViewModel to Model ?? Or it is possible to use somehow AutoMapper? What is the correct way to handle such a scenario?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anatoly Shirokov, 2015-03-19
@ximility

in AutoMapper you can set mapping rules from model to viewmodel and vice versa.
the first one that came across on habré:
habrahabr.ru/post/71820
custom configuration as the author puts it ...
but in general, when I didn’t know about the existence of AutoMapper, I manually moved each field from ViewModel to DbModel,
and I’m sure in most cases I’ll have to do it manually overtake, AutoMapper will not always be able to help out ... although I may be wrong, since I am not an avid fan of the latter.

A
Alexander, 2015-03-19
@primat1987

I figured it out myself. In vain probably created a question. AutoMapper has an overloaded method that maps a source object to an existing object. Those. all fields from the ViewModel will be displayed on the Model, and the "extra" fields of the Model will remain unchanged.

//...
Model fromDb = GetModelFromDbById(id);
Model model = Mapper.Map<ViewModel, Model>(viewModel,  fromDb);

If suddenly this method is not suitable in all cases or you can do something better, write your answers

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question