asp.net-mvc - EntityType 'Category' 没有定义键。定义此 EntityType 的键

标签 asp.net-mvc entity-framework

这个问题在这里已经有了答案:





EntityType has no key defined error

(13 个回答)


5年前关闭。




开发一个基本的 ASP.net MVC 4 应用程序。它是一个简单的产品目录应用程序,其中我有 2 个数据库表(“类别”和“产品”)

“产品”表中有一个“类别 ID”(类别表中的主键)的外键引用。

当我运行应用程序时,我收到错误消息(如下所列)。

System.Data.Entity.Edm.EdmEntityType: : EntityType 'Category' has no key defined. Define the key for this EntityType.

System.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'Category' is based on type 'Category' that has no keys defined

这对于新手来说似乎是一个常见错误,我确实检查了“实体键”的所有相关解决方案没有定义键。但我的问题仍然没有解决,请帮助我理解这个问题以及这个问题的正确解决方案是什么。

下面是我的模型类

分类.cs
namespace ChemicalStore.Models
{
    public partial class Category
    {
        public int CatId { get; set; }
        public string CatName { get; set; }
        public string CatDescription { get; set; }
        public List<Product> Product { get; set; }
    }     
}

Products.cs
namespace ChemicalStore.Models
{
    public class Product
    {
        public int ProductId { get; set; }
        public int CatId { get; set; }
        public string ProductTitle { get; set; }
        public string ProductPrice { get; set; }
        public string ProductDescription { get; set; }
        public string ProductPackage { get; set; }
    }
}

最佳答案

您应该在属性 CatId 之前添加属性 [Key]:

        using System.ComponentModel.DataAnnotations;

        public partial class Category
        {
            [Key]
            public int CatId { get; set; }
            public string CatName { get; set; }
            public string CatDescription { get; set; }
            public List<Product> Product { get; set; }
        }

问题是EF只有在知道表的主键时才能工作。默认情况下,EF 识别为具有名称 Id 的主键属性。如果你的表有另一个主键,你可以用属性[Key]标记它或者用流畅的配置设置Key。

关于asp.net-mvc - EntityType 'Category' 没有定义键。定义此 EntityType 的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13862013/

相关文章:

c# - 'System.Dynamic.DynamicObject' 不包含 'PropertyName' 的定义

c# - 添加jquery.unobtrusive-ajax.js引用后上传为空

c# - 无法确定外键的复合外键顺序

c# - Entity Framework 删除问题(使用wpf)

entity-framework - 在 Entity Framework 中使用 Asp.net Identity 抛出无法从程序集“EntityFramework, Version=6.0”加载类型 .Schema.IndexAttribute'

ASP.NET 图表控件不再适用于 .NET 4

c# - 将匿名类型传递给 MVC ViewData.Model 是否安全?

asp.net-mvc - MVC4 Azure 部署找不到网页或 WebMatrix 引用

entity-framework - EF 在运行时从 Type 获取 dbset 名称

c# - 在 Entity Framework 中删除多对多集合的问题