Why is MVC3 not scaffolding my foreign key columns

泄露秘密 提交于 2020-02-01 08:17:21

问题


I'm trying to use MVC 3 with EF 4.1 using code first and am following Scott Guthries tutorial http://weblogs.asp.net/scottgu/archive/2011/05/05/ef-code-first-and-data-scaffolding-with-the-asp-net-mvc-3-tools-update.aspx.

The issue I'm having is that when I create the products controller and the related scaffolded views, there is no "category" column being created in any of the views ("edit", "create", "index" etc), which according to the tutorial should be created.

I've traced the reason why the column is not being shown is because of the t4 templates... it is failing a check to see if it is a bindable type in order to display the property as a column.

The logic for checking if it is bindable is:

bool IsBindableType(Type type) {
return type.IsPrimitive || bindableNonPrimitiveTypes.Contains(type);
}

Where bindableNonPrimitiveTypes is a fixed list:

static Type[] bindableNonPrimitiveTypes = new[] {
typeof(string),
typeof(decimal),
typeof(Guid),
typeof(DateTime),
typeof(DateTimeOffset),
typeof(TimeSpan),
};

I have just installed VS2010 sp1, EF 4.1 and the MVC3 Tools Update referenced by the tutorial. I'm sure I've followed all the steps...

Where am I going wrong/What am I missing?


回答1:


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.



来源:https://stackoverflow.com/questions/6319802/why-is-mvc3-not-scaffolding-my-foreign-key-columns

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