繁体   English   中英

EntityType''没有定义键。 定义此EntityType的键。 -C#Web API实体框架

[英]EntityType ' ' has no key defined. Define the key for this EntityType. - C# Web API Entity Framework

即使在此论坛上阅读了[key]属性,我仍然遇到以下错误:

EntityType'EbayItem'没有定义键。 定义此EntityType的键

这是我的context类:

public class PeopleContext : DbContext
{
    public DbSet<EbayItem> EbayItems { get; set; }
    public DbSet<EbayUser> EbayUsers { get; set; }
} 

这是我的EbayItem.cs

[Table("tbl_items")]
public class EbayItem
{
    [key]
    public int Item_ID { get; set; }
    public string Item { get; set; }
    public string Category { get; set; }
    public int Bids { get; set; }

    public int User_ID { get; set; }
    public EbayUser User { get; set; }
}

这是我的EbayUser.cs

[Table("tbl_users")]
public class EbayUser
{
    public int User_ID { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public string Age { get; set; }

    public IList<EbayItem> EbayItems { get; set; }
}

这是我的Get()

// GET: api/Ebay
public IEnumerable<EbayItem> Get()
{
    PeopleContext context = new PeopleContext();
    List<EbayItem> items = context.EbayItems.Include(p => p.User).ToList();

    return items;
}

这是我的桌子设计的屏幕截图:

tnl_users

tbl_items

不好意思的命名约定是因为我只是将这个特定项目用作游乐场来冒险使用Entity Framework,但要更深入一些。

您是否具有带有大写字母的“关键字”属性? 或者,您也可以指定列ID名称,例如: 如何在EF-Code-First中指定主键名称

这可能是因为您尚未为“ EbayItem”表定义键。 您可以在此处找到更多信息:

https://gilesey.wordpress.com/tag/entitytype-has-no-key-defined/

请记住,如果您不想使用映射属性,则需要正确使用约定来映射表。 只需在您的EbayItem表属性上添加[key]:

[Table("tbl_items")]
public class EbayItem
{
    [Key]
    public int Item_ID { get; set; }
    public string Item { get; set; }
    public string Category { get; set; }
    public int Bids { get; set; }

    public int User_ID { get; set; }
    public EbayUser User { get; set; }
}

如果您在映射关系时遇到问题,建议您检查命名约定,或者使用Fluent API明确命名列和关系https://docs.microsoft.com/zh-cn/ef/ef6/modeling/code-first/fluent /关系

您应该指定EbayItem.User_IDEbayItem.User导航属性的外键。 您可以使用ForeignKey属性执行此操作。 还要在导航属性上使用虚拟关键字。

[Table("tbl_items")]
public class EbayItem
{
    [Key]
    public int Item_ID { get; set; }
    public string Item { get; set; }
    public string Category { get; set; }
    public int Bids { get; set; }

    public int User_ID { get; set; }
    [ForeignKey("User_ID")]
    public virtual EbayUser User { get; set; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM