加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-2 – 使用或不使用AutoMapper的“合并”模型和ViewM

发布时间:2020-12-15 22:17:43 所属栏目:asp.Net 来源:网络整理
导读:我目前正在使用ViewModels将我的Views与实际的Model结构分开. 例如,我有一个用户持久性实体和一个包含所有信息的MyProfile ViewModel,用户可以自己更改. 对于从User到MyProfile的转换,我使用的是Automapper. 现在用户回复了他的(更改的)信息后,我需要保存这
我目前正在使用ViewModels将我的Views与实际的Model结构分开.

例如,我有一个用户持久性实体和一个包含所有信息的MyProfile ViewModel,用户可以自己更改.
对于从User到MyProfile的转换,我使用的是Automapper.

现在用户回复了他的(更改的)信息后,我需要保存这些信息.但是ViewModel中的信息并不完整,当AutoMapper从ViewModel创建用户持久性实体时,重要信息会丢失.

我不想将此信息公开给视图层,尤其是隐藏的表单元素.

所以我需要一种方法将ViewModel合并到持久性实体中.我可以使用AutoMapper执行此操作,还是必须手动执行此操作?

例:

我的用户类包含ID,名字,姓氏,用户名和密码.用户应该只在他的个人资料中编辑他的名字和姓氏.因此,我的ProfileViewModel包含ID,名字和姓氏.从表单中回发信息后??,Automapper从传输的ProfileViewModel创建一个User对象,在此对象中只设置ID,Firstname和Lastname.将此实体提供给我的存储库时,我丢失了用户名和密码信息.

解决方法

So i need a way to merge a ViewModel into a persistence entity. Can I
do that with AutoMapper,or do I have to do it manually?

是的,你可以用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");
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读