Why is MVC3 not scaffolding my foreign key columns

瘦欲@ 提交于 2019-12-04 17:24:53

I believe that it does work as described in the tutorial - I just went through that tutorial right now and got the expected result (it did scaffold a "Category" column and drop-down list).

My best guess about why it didn't work in your case is that perhaps you missed the CategoryID property from the Product class, or maybe you called it something else. For scaffolding to detect the FK relationship, it's necessary for your entity to have both a "navigation" property (in this case, Category, of type Category) and a "foreign key" property (in this case CategoryID of type int) - without those it won't infer the relationship and hence you wouldn't get the dropdown.

In case it helps, here's the full code for the model classes that you can copy and paste into your project:

public class Product
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int CategoryID { get; set; }
    public decimal? UnitPrice { get; set; }
    public int UnitsInStock { get; set; }

    public virtual Category Category { get; set; }
}

public class Category
{
    public int CategoryID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

public class StoreContext : DbContext
{
    public DbSet<Product> Products { get; set; }
    public DbSet<Category> Categories { get; set; }
}

Remember to compile your code before using the "Add Controller" window, otherwise it will not realise that you've changed the code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!