gpt4 book ai didi

asp.net-mvc - 如何将editmodel/postmodel突变为域模型

转载 作者:行者123 更新时间:2023-12-04 04:31:29 25 4
gpt4 key购买 nike

在 ASP.NET MVC 项目中,我们使用 AutoMapper 从域模型映射到 View 模型 - 有时还会在这样做的同时展平层次结构。这就像一个魅力,使我们的 View 的渲染逻辑非常精简和简单。

当我们想从 viewmodel(或 postmodel 或 editmodel)转到域模型时,困惑就开始了,尤其是在更新对象时 .我们不能使用自动/双向映射,因为:

  • 我们将不得不取消扁平化的层次结构
  • 域模型上的所有属性都必须是可变的/具有公共(public) setter
  • 来自 View 的更改并不总是被映射回域的平面属性,有时还需要调用诸如“ChangeManagerForEmployee()”之类的方法或类似的方法。

  • 这也在 Jimmy Bogards 的文章中有所描述: The case for two-way mapping in AutoMapper ,但是没有详细描述这个问题的解决方案,只是他们去:

    From EditModel to CommandMessages – going from the loosely-typed EditModel to strongly-typed, broken out messages. A single EditModel might generate a half-dozen messages.



    在一个类似的 SO question Mark Seeman有答案他提到的地方

    We use abstract mappers and services to map a PostModel to a Domain Object



    但是细节 - 概念和技术实现 - 被遗漏了。

    我们现在的想法是:
  • 在 Controller 的操作方法中接收 FormCollection
  • 获取原始域模型并将其展平为 viewModelOriginal 和 viewModelUpdated
  • 使用 UpdateModel() 将 FormCollection 合并到 viewModelUpdated 中
  • 使用一些通用的辅助方法来比较 viewModelOriginal 和 viewModelUpdated
  • A)像 Jimmy Bogard 那样生成 CommandMessage 或 B)通过属性和方法将差异直接变异到域模型中(可能直接通过 AutoMapper 映射 1-1 属性)

  • 有人可以提供一些示例,说明它们是如何从 FormCollection 通过editmodel/postmodel 到域模型的吗? “CommandMessages”还是“抽象映射器和服务”?

    最佳答案

    我使用以下模式:

    [HttpPost]
    public ActionResult Update(UpdateProductViewModel viewModel)
    {
    // fetch the domain model that we want to update
    Product product = repository.Get(viewModel.Id);

    // Use AutoMapper to update only the properties of this domain model
    // that are also part of the view model and leave the other properties unchanged
    AutoMapper.Map<UpdateProductViewModel, Product>(viewModel, product);

    // Pass the domain model with updated properties to the DAL
    repository.Update(product);

    return RedirectToAction("Success");
    }

    关于asp.net-mvc - 如何将editmodel/postmodel突变为域模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11313822/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com