Reputation: 51291
I need to pull the data from DB and fill the view model, is there any better way to do this? Currently I'm doing something like this.
ViewModel vm = new ViewModel();
var recentBill = context.Money.Take(10);
foreach (var r in recnetBill)
{
vm.lst.Add(r);
}
Upvotes: 4
Views: 5614
Reputation: 3407
I would recommend you to prevent possibility of changing ViewModel.lst, i.e. lst's type should be IEnumerable instead of List/IList (of course if your further code doesn't require List functionality).
Furthermore, I suppose you don't modify lst reference, so you could remove setter and initialize lst via constructor.
public class ViewModel
{
public ViewModel(IEnumerable<Money> lst)
{
this._lst = lst;
}
private readonly IEnumerable<Money> _lst;
IEnumerable<Money> Lst
{
get
{
return this._lst;
}
}
// other properties
}
public ActionResult GetMonies()
{
var model = new ViewModel(context.Money.Take(10).ToArray());
return View(model);
}
This approach guarantees that consumers of your code will not modify your ViewModel.Lst accidentally.
Upvotes: 1
Reputation: 73113
Assuming your ViewModel looks like this:
public class ViewModel
{
IEnumerable<Money> lst { get; set; }
// other properties
}
Just do this:
public ActionResult GetMonies()
{
var monies = context.Money
.Take(10)
.ToList();
var model = new ViewModel { lst = monies };
return View(model);
}
Upvotes: 0
Reputation: 40202
IEnumerable
has the ToList()
function which returns a list of said type.
vm.lst = context.Money.Take(10).ToList(); // returns a List<Money>
Upvotes: 2