I'm working on an ASP.NET MVC 5 project in which I'm trying to build a controller from a MVC View Model. That ViewModel brings together 6 tables which I need to show in the views. Its my understanding that using MVC ViewModels is one way of showing multiple tables in a view. Anyway, I'm getting the following error message:
Error
There was an error running the selected code generator: 'Unable to retrieve metadata for
'PrismSmallTasks.ViewModels.ManageInterviewVM'. One of more validation errors were
detected during model generation:
ManageInterviewVM:: EntityType 'ManageInterviewVM' has no key defined.
Define the key for this EntityType.
ManageInterviewVMs: EntityType: EntitySet 'ManageInterviewsVMs' is based on
type 'ManageInterviewVM' that has no keys defined.
There's no key in the ManageInterviewVM ViewModel. That's because it's comprised of lists of the tables represented in the models that are in the VM. And each of those model classes do have a column that has a key defined for it.
For example, here's ManageInterviewVM:
public class ManageInterviewVM
{
public List<FieldRecord> FieldRecords { get; set; }
public List<TaskList> TaskLists { get; set; }
public List<InterviewARVTreatment> InterviewARVTreatments { get; set; }
public List<Note> Notes { get; set; }
public List<Risk> Risks { get; set; }
public List<Interview1> Interviews { get; set; }
}
And here's a partial listing of one of those tables as it is defined in the model class:
public partial class TaskList
{
[Key]
public int ID_TaskList { get; set; }
[Required]
[StringLength(15)]
public string CD_TaskListType { get; set; }
public int? ID_Profile { get; set; }
public int? ID_FieldRecord { get; set; }
public int? ID_Interview { get; set; }
So, I don't know what I'm missing. Why is this error showing up and how I can resolve it?
Your ViewModels should be completely dissociated from your Data Context (Data Access Layer). Only your domain models should deal with the DAL. ViewModels are only for displaying specific information to the view.
So after you create your ViewModel.. you try and create your view. When you arrive at this screen:
Since viewmodels are not supposed to be associated with the data access layer, you can just delete what is auto-populated in the 'Data context class' and then you should be able to create your view.
If you fall into the trap of thinking that you need to define keys for your viewmodel.. then your viewmodel class will be added to your connection string's class (dbcontext class).. which is a no-no.
You need to query the database using your domain models.. then you assign those values to your ViewModels properties that you want to display.
Hope this helps!