“No Key Defined” error message, when creating a view for a view model

岁酱吖の 提交于 2019-12-12 01:36:15

问题


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.



来源:https://stackoverflow.com/questions/36367390/no-key-defined-error-message-when-creating-a-view-for-a-view-model

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!