asp.net-mvc-2 – 使用或不使用AutoMapper的“合并”模型和ViewModel?
|
我目前正在使用ViewModels将我的Views与实际的Model结构分开. 例如,我有一个用户持久性实体和一个包含所有信息的MyProfile ViewModel,用户可以自己更改. 现在用户回复了他的(更改的)信息后,我需要保存这些信息.但是ViewModel中的信息并不完整,当AutoMapper从ViewModel创建用户持久性实体时,重要信息会丢失. 我不想将此信息公开给视图层,尤其是隐藏的表单元素. 所以我需要一种方法将ViewModel合并到持久性实体中.我可以使用AutoMapper执行此操作,还是必须手动执行此操作? 例: 我的用户类包含ID,名字,姓氏,用户名和密码.用户应该只在他的个人资料中编辑他的名字和姓氏.因此,我的ProfileViewModel包含ID,名字和姓氏.从表单中回发信息后,Automapper从传输的ProfileViewModel创建一个User对象,在此对象中只设置ID,Firstname和Lastname.将此实体提供给我的存储库时,我丢失了用户名和密码信息. 解决方法
是的,你可以用AutoMapper做到这一点.例如: public class Model
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ViewModel
{
public string Name { get; set; }
}
class Program
{
static void Main()
{
// define a map (ideally once per appdomain => usually goes in Application_Start)
Mapper.CreateMap<ViewModel,Model>();
// fetch an entity from a db or something
var model = new Model
{
Id = 5,Name = "foo"
};
// we get that from the view. It contains only a subset of the
// entity properties
var viewModel = new ViewModel
{
Name = "bar"
};
// Now we merge the view model properties into the model
Mapper.Map(viewModel,model);
// at this stage the model.Id stays unchanged because
// there's no Id property in the view model
Console.WriteLine(model.Id);
// and the name has been overwritten
Console.WriteLine(model.Name);
}
}
打印: 5 bar 并将其转换为典型的ASP.NET MVC模式: [HttpPost]
public ActionResult Update(MyViewModel viewModel)
{
if (!ModelState.IsValid)
{
// validation failed => redisplay view
return View(viewModel);
}
// fetch the domain entity that we want to udpate
DomainModel model = _repository.Get(viewModel.Id);
// now merge the properties
Mapper.Map(viewModel,model);
// update the domain model
_repository.Update(mdoel);
return RedirectToAction("Success");
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net – ExecuteScalar抛出NullReferenceException
- Asp.Net:在iis中调试网站
- 如何防止ASP.NET站点的图像热链接?
- asp.net – 拒绝访问web.config中的“admin”文件夹
- asp.net – 什么是建议替代常见的破坏app_offline.htm黑客?
- asp.net-mvc – Sql Views的流畅Nhibernate映射
- 会员资格,SimpleMembership,ASP.NET身份之间有什么区别?
- asp.net-core – 使用IdentityServer4生成访问令牌,无需密码
- 如何在IIS 7上的经典ASP中启用大型文件的上传?
- asp.net-mvc – 使用LINQ to SQL在ASP.NET MVC中建模多对多
