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

本文关键字:查询 视图 模型 控制器 NET MVC ASP | 更新日期: 2023-09-27 18:09:28

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

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文件夹中创建了静态类。谢谢你!

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

最近我读了几篇关于重构控制器和将代码转移到应用程序服务的好文章:

7 Keep Controllers Thin

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

最佳实践- Skinny Controllers

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;
    }
    ...
}

请让我知道如果有人有其他的想法,想法等。