Viewmodel has no key defined

Even if it's an old answered question I thought this might help: When creating a view (i suspect partial view in this case), remove the Data Context Class value. If it is set, even though you are creating a non-entity framework based view, Visual studio thinks you are using Entity Framework so it throws that error.


Does it have to have a primary key?

No. View model is a simple POCO class. Unless you want to do some custom validation in your UI/Validation/Business layer, you do not need to decorate any property with [Key] attribute.

Does it need to be in my db and added as an EF entity?

No. View model's purpose it to communicate data between your view and the action methods. You will read data from one view model object and save that in 2 or more tables as needed. view models should be lean and flat because it is for the specific view.

The error you are seeing is may be a bug in visual studio. Why don't you manually create an action method, a view (don't select the model in the wizard) and update the view to use your view model as the model


(If using code first, or step to second step)First, you have to check the model(entity) used by ViewModel(and you use to connect to database directly) in which attribute(column) have set "[Key]" Data Annotation.

Second, you have to contain the primary key attribute(column) in the ViewModel class, and give it "[Key]" Data Annotation in the ViewModel class. (Beacause you have to assign a key for computer to distinguish each row.)

Third, rebuild your whole project, then you can successfully use built-in template to generate View.