0

I'm working with ASP.NET MVC5 and following the code-first method of development for my application.

I'm having some trouble understanding what the best course of action would be to take in this situation. I have the default ASP.NET Application User model and I created an event model. Application users can have multiple events. I want to create a profile page, which pulls data from the application user model and the event model. Reading through a bunch of different posts it seems like I would create a ViewModel? This is somewhat confusing because this means I am mixing elements of MVVM and MVC?

Is this the best course of action? To me it doesn't make sense to create a new model that combines these items together, in addition with the code first method, a new table created for this model which I do not want to happen.

ChrisRiv91
  • 91
  • 3
  • 1
    A view model is the correct approach with MVC. All views should be based on view models, not data models. It would contain (at least) properties `User User` and `IEnumerable Events` (but preferably `UserViewModel User` and `IEnumerable Events`). You initialize it in the controller, populate it with data from the data models and return it to the view. Not sure why you think a _"new table"_ is required? Refer [What is a ViewModel in MVC](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Apr 29 '15 at 04:13
  • My concern was if that I created a new model that joined these elements Users and Events, the code first migration would create a new table. I guess, the underlying question is: If I create this ViewModel class, how do I target the proper elements from the respective models (users and events). – ChrisRiv91 Apr 29 '15 at 04:16
  • Create a separate folder in you app (say) ViewModels for these classes. In the controller in might look something like, `var model = new UserEventModel(); model.User = db.Users.Find(ID); model.Events = db.Events.Where(e => e.UserId = ID); return View(model)` –  Apr 29 '15 at 04:23
  • Alright, this is starting to make some sense now. Let me mess around with it and see if I can get it work. Thanks Stephen!! – ChrisRiv91 Apr 29 '15 at 04:27
  • @ChrisRiv91 This is a good explanation of how to use viewModels http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc . This is the best approach as Stephen mentioned, and at least that you add the class to the DbContext it won't alter your migrations. – nramirez Apr 29 '15 at 04:31

0 Answers0