簡體   English   中英

代碼優先實體框架中的外鍵

[英]Foreign Key in Code First Entity Framework

我的問題是這個。 假設我有一個Category類和Product類。 它們的實現方式如下:Category:

public class Category
    {
        public Category()
        {
            this.Products = new ObservableCollection<Product>();
        }

        public int CategoryId { get; set; }
        public string Name { get; set; }

        public virtual ObservableCollection<Product> Products { get; private set; }
}

和產品:

public  class Product
    {
        public int ProductId { get; set; }
        public string Name { get; set; }

        public int CategoryId { get; set; }
        public virtual Category Category { get; set; }
    }

我的問題是這個。 如果它們的ID名稱都為“ Id”,我該如何在Category和Product之間設置相同的關系? 在此示例中,我可以輕松地將CategoryId放入產品中,因為ID具有不同的名稱。 如果他們有相同的名字怎么辦? 我該怎么辦? 謝謝。

我認為只是將其ID重命名為“ Id”即可按您期望的那樣完美地工作。

public class Category
{
    public Category()
    {
        this.Products = new ObservableCollection<Product>();
    }

    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ObservableCollection<Product> Products { get; private set; }
}
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int CategoryId { get; set; }
    public virtual Category Category { get; set; }
}

結果

數據庫結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM