gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:52:42 26 4
gpt4 key购买 nike

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





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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com