MVC. I am passing data to the view in my model. In my repository I map the linq result to the model. In the controller I send the data. Which one should I do:
List<PersonModel> people = new List<PersonModel>();
people = repo.GetPersonList();
return View(people);
Or
List<PersonModel> people = repo.GetPersonList();
return View(people);
As I mentioned, in the repo I map the result to the model, with a new model instance:
var query = from p in _db.Person
orderby f.LastName
select new PersonModel
{
Id = f.PersonId,
LastName = f.LastName
};
return query.ToList();
Either one works. I use the second one because by my thinking, the repo is creating a new model then passing it to the controller when I call the repo.GetPersonList function. Should I create a new instance in the controller as well, or continue as I am?
Go with the second.
Your first snippet has a redundant new List<T>
call which allocates a new list, while the next line overrides that reference with a newly created list from your repo
. Absolutely no need for that.
如果在您的Controller上, repository
负责提供ViewModel并且您没有允许Controller将新的PersonModel
添加到ViewModel,那么您应该坚持使用第二个 。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.