Pure POCO entity update problem in repository pattern

后端 未结 3 1049
迷失自我
迷失自我 2020-12-09 13:48

I have a problem in my UserRepository in which I want to update a user. I dont want certain fields updated, such as password, unless specified. For example, When I pass the

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 14:24

    You should use view models. View models are classes which are specifically tailored to the needs of a view and contain only the properties needed by this given view. So your controller action should look like this:

    [HttpPost]
    public ActionResult Update(UserViewModel model) { ... }
    

    instead of:

    [HttpPost]
    public ActionResult Update(User model) { ... }
    

    Inside the controller action you could map between the view model and the model. AutoMapper is a great tool that could simplify this task.

    You should really be very careful and never expose your models like this. Always use view models to and from a view. Just imagine if there was an IsAdministrator boolean property on your model.

提交回复
热议问题