Friday, 15 August 2014

c# - ASP.NET MVC - Querying into View Models Outside the Controller -



c# - ASP.NET MVC - Querying into View Models Outside the Controller -

i have couple of repositories homecoming entities (persistence models) list of view models. mappings of entities view models happen in controller. example:

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 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, ... }); homecoming view(viewmodellist); } }

question: best way (pattern?, location?) store code (mappings, url formatters, etc.) outside controller? end creating static classes in models folder. give thanks you!

recently i've read few nice articles refactoring controllers , moving code application services:

7 maintain controllers thin

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

best practices – skinny controllers

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

so did refactoring , controller looks:

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); homecoming view(viewmodellist); } ... }

created new application service:

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 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, ... }); homecoming viewmodellist; } ... }

please allow me know if has other thoughts, ideas, etc.

c# asp.net-mvc design-patterns domain-driven-design

No comments:

Post a Comment