“No Key Defined” error message, when creating a vi

2019-09-02 22:13发布

问题:

Currently I am creating a project following 'MVC Music Store' tutorial, when come to create a view for "ShoppingCartViewModel", it always shows the error that tells me that there is no Key definied. The error message is: Entity type'ShoppingCartViewModel' has no key defined....

Here is the original code from the tutorial:

namespace MyMVStore.ViewModels
{
     public class ShoppingCartViewModel
    {

       public List<Cart> CartItems { get; set; }
       public decimal? CartTotal { get; set; }
   }
}

Here is what I updated:

//[NotMapping]
namespace MyMVStore.ViewModels
{
     public class ShoppingCartViewModel
    {
       [Key] //my code
       public int Id { get; set; } // my code
       public List<Cart> CartItems { get; set; }
       public decimal? CartTotal { get; set; }
   }
}

I put [Key] and Id to the model, seems not working. I also tried to add [Notmapping], it doesn't work either. The error massage still showing up when I tried to create the view for this model.

回答1:

All you need to do is remove the DataContext class from the dropdown. It's an editable dropdown, so you can just highlight it and delete it.
It works fine after you do that.



回答2:

You most likely have declared DbSet in your context class, which is associated with EF. Remove the declaration to make it a non-table model.