使用EF为模型创建控制器(无密钥错误)

时间:2015-08-10 09:47:09

标签: c# entity-framework asp.net-mvc-4

我正在尝试使用基于以下模型的脚手架创建一个控制器(没有先前创建的上下文,但我选择了在控制器旁边创建它的选项):

namespace MvcMusicStorePractice.Models
{
    public class Album
    {     
        public virtual int AlbumId { get; set; }
        public virtual int GenreId { get; set; }
        public virtual int ArtistId { get; set; }
        public virtual string Title { get; set; }
        public virtual decimal Price { get; set; }
        public virtual string AlbumArtUrl { get; set; }
        public virtual Genre Genre { get; set; }
        public virtual Artist Artist { get; set; }
    }
}

但我一直收到以下错误:

  

专辑:: EntityType'专辑'没有定义键。定义此EntityType的密钥。

我尝试了以下解决方案:

  • [Key]属性添加到AlbumId;
  • 将public virtual int AlbumId更改为public int Id。
然而,它仍然不起作用。有谁知道问题是什么?

1 个答案:

答案 0 :(得分:1)

为了使用实体框架,每个实体都需要一个密钥。这就是EF跟踪其缓存中的对象,将更新发布回底层数据存储以及将相关对象链接在一起的方式:

namespace MvcMusicStorePractice.Models
{ 
    public class Album
    {   
        [Key]
        public int AlbumId { get; set; }
        public int GenreId { get; set; }
        public int ArtistId { get; set; }
        public string Title { get; set; }
        public decimal Price { get; set; }
        public string AlbumArtUrl { get; set; }

        public virtual Genre Genre { get; set; }
        public virtual Artist Artist { get; set; }
    }
}

注意[key]注释,使该字段成为PK。

另外,请确保仅对外来物品使用“虚拟”(仅限流派和艺术家)/