c# - 在哪里将业务模型转换为 View 模型?

标签 c# asp.net-mvc entity-framework repository-pattern unit-of-work

在我的ASP.NET MVC应用程序中,我使用工作单元和存储库模式进行数据访问。

使用工作单元类和在其中定义的存储库,我正在 Controller 中获取相关的实体集。以我的初学者知识,我可以想到两种获取业务模型并将其转换为 View 模型的方法。

  • 存储库将业务模型返回给 Controller ,该模型比映射到 View 模型或
  • 存储库本身将业务模型转换为 View 模型,然后将其返回给 Controller 。

  • 目前,我正在使用第一种方法,但是对于具有很多属性的 View 模型,我的 Controller 代码开始显得难看且冗长。

    另一方面,我在想,因为我的存储库被称为UserRepository(例如),它应该直接返回业务模型,而不是仅对单个 View 有用的某些模型。

    您认为大型项目的最佳实践是哪一种?还有其他方法吗?

    最佳答案

    存储库应返回域模型,而不是 View 模型。至于模型和 View 模型之间的映射,我个人使用AutoMapper,所以我有一个单独的映射层,但是从 Controller 调用了该层。

    以下是典型的GET Controller 操作的样子:

    public ActionResult Foo(int id)
    {
        // the controller queries the repository to retrieve a domain model
        Bar domainModel = Repository.Get(id);
    
        // The controller converts the domain model to a view model
        // In this example I use AutoMapper, so the controller actually delegates
        // this mapping to AutoMapper but if you don't have a separate mapping layer
        // you could do the mapping here as well.
        BarViewModel viewModel = Mapper.Map<Bar, BarViewModel>(domainModel);
    
        // The controller passes a view model to the view
        return View(viewModel);
    }
    

    当然,可以使用自定义操作过滤器来缩短哪些操作,以避免重复的映射逻辑:
    [AutoMap(typeof(Bar), typeof(BarViewModel))]
    public ActionResult Foo(int id)
    {
        Bar domainModel = Repository.Get(id);
        return View(domainModel);
    }
    

    AutoMap定制操作过滤器订阅OnActionExecuted事件,截获传递给 View 结果的模型,调用映射层(在我的情况下为AutoMapper)将其转换为 View 模型并将其替换为 View 。当然, View 是根据 View 模型强类型化的。

    关于c# - 在哪里将业务模型转换为 View 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11470164/

    相关文章:

    asp.net-mvc - 父子关系的 MVC 路由

    c# - 为什么我应该返回 ActionResult 而不是对象?

    c# - 在 C# 和 C++ 之间传输图像数据

    css - 直接向MVC中的元素添加样式而不添加类

    entity-framework - 我应该坚持使用 Entity Framework 吗?

    entity-framework - Entity Framework 核心 : “Invalid attempt to call ReadAsync when reader is closed”

    c# - 在 Entity Framework Core 的系统版本时态表中查询数据

    c# - 尝试在 azure 存储帐户/Blob 上设置 cors 时出现无尽错误

    c# - 如何加快3个联合表中的选择速度

    c# - 删除操作和查询字符串之间的斜杠(就像 SO 的搜索行为一样)