[英]How can I convert a list of domain objects to viewmodels on the Controller in ASP.NET MVC
I'd like to know the best way of converting a list of domain object I retrieve into custom ViewModels in the controller 我想知道将我检索到的域对象列表转换为控制器中的自定义ViewModel的最佳方法
eg 例如
IList<Balls> _balls = _ballsService.GetBalls(searchCriteria);
into 成
IList<BallViewModels> _balls = _ballsService.GetBalls(searchCriteria);
it doesn't have to be exactly as I've outlined above ie it doesn't have to be an IList and if not accessing the service directly and instead go thru some other layer that converts the objects to viewmodels then that is ok too. 它不必像我上面概述的那样,即它不必是IList,如果不是直接访问服务,而是通过一些其他层将对象转换为viewmodels,那也没关系。
thanks 谢谢
For simple objects you could just use Linq: 对于简单的对象,您可以使用Linq:
IList<BallViewModel> _balls = _ballsService.GetBalls(searchCriteria)
.Select(b => new BallsViewModel
{
ID = b.ID,
Name = b.Name,
// etc
})
.ToList();
That can get pretty repetitive though, so you may want to give your BallViewModel class a constructor that accepts a Ball and does the work for you. 但是,这可能会非常重复,因此您可能希望为BallViewModel类提供一个接受Ball的构造函数,并为您完成工作。
Another approach is to use a library like AutoMapper to copy the properties (even the nested ones) from your domain object to your view model. 另一种方法是使用类似AutoMapper的库将属性(甚至是嵌套的属性)从域对象复制到视图模型。
Probably a bit of Linq, something along the lines of 可能有点像Linq,有点像
var ballQuery = from ball in _ballsService.GetBalls(searchCriteria)
select new BallViewModels
{
Diameter = ball.Diameter,
color = ball.Color,
...
}
IList<BallViewModels> _balls = ballQuery.ToList();
Either that or the question is more complicated than I think... 无论是那个或问题比我想的更复杂......
I use AutoMapper to do this all the time. 我使用AutoMapper一直这样做。 It's really flexible and has worked for me without any troubles so far. 它非常灵活,到目前为止我没有任何麻烦。
First you set up a map like during your app's initialization: 首先,在应用初始化期间设置地图:
Mapper.CreateMapping<Balls, BallViewModel>();
And whenever you need to map the objects, you would do this: 无论何时需要映射对象,都可以这样做:
Mapper.Map<IList<Balls>, IList<BallViewModel>>(_ballsService.GetBalls());
Like I said, it's very flexible and you can modify how the mapping happens for each property using a fluent API. 就像我说的那样,它非常灵活,您可以使用流畅的API修改每个属性的映射方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.