簡體   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