ASP.NET MVC - 查询控制器外的视图模型

时间:2014-06-20 12:27:35

标签: c# asp.net-mvc design-patterns domain-driven-design

我有几个存储库将实体(持久性模型)返回到视图模型列表中。实体到视图模型的所有映射都发生在控制器中。例如:

public class TestController : Controller
{
    private readonly ITestRepository repository;

    public TestController (ITestRepository repository)
    {
        this.repository = repository;
    }

    public ActionResult Index(SomeFilter filter)
    {
        var viewModelList = repository.GetTestEntityBy(filter.TestId, filter.Name) // returns IQueryable<TestEntity>
            .Select(x => new TestViewModel // linq projection - mapping into the list of viewModel
            {
                Id = x.Id,
                Name = SomeFormatter.FormatName(
                    x.TestId,
                    x.TestAddress1,
                    x.TestAddress2),
                Url = UrlFormatter.Format(x.TestName, Url.Action("ChangeValue", "TestController", new { x.id })),
                AllergyType = x.TestType
                Notes = x.Notes,
                ...
            });

        return View(viewModelList);
    }
}

问题:在控制器外部存储此代码(映射,url格式化程序等)的最佳方法(模式?,位置?)是什么?最终我最终在Models文件夹中创建了静态类。 谢谢!

1 个答案:

答案 0 :(得分:1)

最近我读了一些关于重构控制器并将代码移动到应用程序服务的好文章:

7保持控制器薄

http://www.codemag.com/Article/1405071

最佳实践 - 瘦控制器

http://www.arrangeactassert.com/asp-net-mvc-controller-best-practices-%E2%80%93-skinny-controllers/

所以我做了一些重构,控制器现在看起来:

public class TestController : Controller
{
    private readonly ITestApplicationService service;

    public TestController (ITestApplicationService service)
    {
        this.service = service;
    }

    public ActionResult Index(SomeFilter filter)
    {
        var viewModelList = service.GetModelList(filter, Url);
        return View(viewModelList);
    }
    ...
}

创建了一个新的应用程序服务:

public interface ITestApplicationService
{
    IQueryable<TestViewModel> GetModelList(SomeFilter filter, UrlHelper url);
    void Save(TestViewModel model);
    void Delete(int id);
}

public class TestApplicationService
{
    private readonly ITestRepository repository;

    public TestApplicationService(ITestRepository repository)
    {
        this.repository = repository;
    }

    public IQueryable<TestViewModel> GetModelList(SomeFilter filter, UrlHelper url)
    {
       var viewModelList = repository.GetTestEntityBy(filter.TestId, filter.Name) // returns IQueryable<TestEntity>
        .Select(x => new TestViewModel // linq projection - mapping into the list of viewModel
        {
            Id = x.Id,
            Name = SomeFormatter.FormatName(
                x.TestId,
                x.TestAddress1,
                x.TestAddress2),
            Url = UrlFormatter.Format(x.TestName, url.Action("ChangeValue", "TestController", new { x.id })),
            AllergyType = x.TestType
            Notes = x.Notes,
            ...
        });

        return viewModelList;
    }
    ...
}

如果有人有其他想法,想法等,请告诉我。