简体   繁体   中英

Foreign Key in Code First Entity Framework

My question is this. Let's say I have a Category class and Product class. And they are implemented like this : 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; }
}

And Product :

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

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

My question is this. If their id names were both "Id", how could I set the same relationship between Category and Product? In this example I can easily put CategoryId in product because the IDs have different names. What if they had the same name? What should I do? Thanks.

I think just renaming their Id(s) to "Id" work perfectly as you expected.

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; }
}

Result

数据库结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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