Should I create a new model?

MVC. I am passing data to a view in my model. In my repository, I am mapping the linq result to the model. In the controller, I am sending 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 output from the model to a new instance of the model:

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 in my opinion the repo creates a new model and then passes it to the controller when I call the repo.GetPersonList function. Should I create a new instance in the controller, or continue as I do?

+3


source to share


2 answers


Go with the second.



Your first snippet has a redundant call new List<T>

that allocates a new list, and the next line overrides that link with the newly created list from repo

. Absolutely unnecessary for this.

+4


source


If your controller has no responsibility for repository

providing the ViewModel to allow the controller to add a new one PersonModel

to the ViewModel, then you should definitely stick with the second .



+1


source







All Articles