Adding ViewModel class adds codefirst model to database c# entity-framework entity-framework-6


I need a view-model in my ASP.NET MVC 5 project, but when I added one to the models folder, a new entity was added to the database and I was forced to add a migration and update my database. I do not want this to happen, as it is a view-model I am adding and not a model I need to persist back to the database. I want to scaffold some of the controller and views so I have added a primary key to the class. I did not add the newly created view-model to my DbContext class.


    public class RolesViewModel 
        public int RolesViewModelId { get; set; }
        public string Role { get; set; } 

Is there a way to create a view-model that doesn't automatically get added to the DbContext class, and therefore cause the data model to change?

Many thanks,


3/10/2014 5:30:30 AM

Accepted Answer

In your case Scaffolding will add the following code below in your appContext Class

public DbSet<RolesViewModel> RolesViewModel { get; set; }

You can still use scaffolding if you wish, however remember to remove that entry and no table will be created by code first. It will keep your database clean.

8/2/2018 7:22:57 AM

Popular Answer

Whether you call it a view model, an entity, etc. it's just semantics. Everything is just a class, and the context it's used in determines what you refer to it as. In the case of entities, that's adding a reference either explicitly or implicitly in your DbContext, and that's the only way you'll end up with something added to your database. I emphasized the "or implicitly* part because if any class that is referenced in the your DbContext, or any class connected to any class referenced there, also references your "view model", it will end up in your database. Entity Framework will automatically follow your class hierarchies and create tables for all relationships, even if you do not reference a particular class in those hierarchies directly in your DbContext.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow