正确将视图模型映射到实体 [英] Correctly Mapping viewmodel to entity
问题描述
我的实体为:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
我的UserViewModel为
I have my UserViewModel as
public class UserViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
我在控制器中按以下方式使用它们:
I am using these as below in my controller:
//This is called from my view via ajax
public void Save(UserViewModel uv)
{
// this throws error: cannot convert from UserViewModel to Entity.User
MyRepository.UpdateUser(uv);
}
我在存储库类中的UpdateUser如下:
My UpdateUser in repository class is as below:
public void UpdateUser(User u)
{
var user = GetUserDetails(u.Id);
user.Name = u.Name;
user.Address = u.Address;
//using entity framework to save
_context.SaveChanges();
}
如何正确将控制器中的UserViewModel映射到我的实体
How can I correctly map UserViewModel in my controller to my entity
推荐答案
通过使用 AutoMapper 您可以执行以下操作:
By using AutoMapper you can do something like:
public void Save(UserViewModel uv)
{
// this throws error: cannot convert from UserViewModel to Entity.User
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<UserViewModel , User>();
});
User u = config.CreateMapper().Map<User>(uv);
MyRepository.UpdateUser(u);
}
或手动:
public void Save(UserViewModel uv)
{
User u = new User()
{
Id = uv.Id
Name = uv.Name;
Address = uv.Address;
};
MyRepository.UpdateUser(u);
}
如果您更改视图模型和模型,那么手动进行操作不好,那么您也应该更改代码,但是使用Automapper
无需更改代码.
Which is not good to do it manually if you change your view-model and your model then you should change your code also, but with Automapper
you don't need to change the code.
在存储库(DataAccess Core)中使用模型视图不是一个好主意,因此最好保留您的public void UpdateUser(User u)
并且不要对其进行更改,在外部最好将user
传递给UserViewModel
不像您之前所做的那样.
This is not good idea to use model-view in repository (DataAccess Core) so it would be better to keep your public void UpdateUser(User u)
and don't change it, in outside it is better to pass user
to UpdateUser
not UserViewModel
like what you have done before.
我认为没有答复的帖子甚至与我的SOC(关注点分离)都没有关系.
In my opinion non of answered posts doesn't related to SOC (Separation on concerns) even mine...
1-当我通过UserViewModel
时,我违反了SOC ....
1- When I passed UserViewModel
I've violated the SOC ....
2-另一方面,如果我直接在Persentation层中拥有用户,那么我也违反了SOC.
2- In the other side if I got User in Peresentation layer directly I also violated the SOC.
我认为最好的方法是使用中间层作为代理....
I think the best way is a middle layer as proxy....
演示文稿< ---->代理服务器< ---->存储库.
Presentation <----> Proxy <----> Repository.
这篇关于正确将视图模型映射到实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!