2011-06-12 38 views
2

我试图使用MVC 3与EF 4.1使用代码第一,我跟随斯科特Guthries教程http://weblogs.asp.net/scottgu/archive/2011/05/05/ef-code-first-and-data-scaffolding-with-the-asp-net-mvc-3-tools-update.aspx为什么MVC3不脚手架我的外键列

我遇到的问题是,当我创建产品控制器和相关的脚手架视图时,没有在任何视图中创建“类别”列(“编辑”,“创建”,“索引”等),根据教程应该创建。

我追溯了列未显示的原因是因为t4模板...它无法检查它是否是可绑定类型以便将该属性显示为列。

检查,如果它是绑定的逻辑是:

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

凡bindableNonPrimitiveTypes是一个固定列表:

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

我刚刚安装VS2010 SP1,EF 4.1和MVC3工具更新引用由教程。 我确定我已经遵循了所有步骤...

我在哪里错了/我错过了什么?

+1

我认为这个教程可能是错误的,因为我从来没有见过MVC 3脚手架使用DB First自动创建导航属性,无论是否使用SP1或MVC工具更新。 – Tridus 2011-06-12 03:35:56

回答

8

我相信它的工作方式与本教程中描述的一样 - 我刚刚浏览了该教程并获得了预期的结果(它支持“类别”列和下拉列表)。

我最好的猜测是为什么它在你的情况下不起作用,或许你错过了Product类的CategoryID属性,或者你可能称之为别的东西。对于脚手架检测FK关系,您的实体有必要同时拥有“导航”属性(在此例中为Category,类型为Category)和“外键”属性(在此例中为类型为int) - 没有那些它不会推断这种关系,因此你不会得到下拉。

万一有帮助,这里是为您可以复制并粘贴到您的项目模型类的完整代码:

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

记得使用“添加控制器”窗口之前编译代码,否则不会意识到你已经改变了代码。

+1

谢谢史蒂文那是问题,我有一个类型属性错字 – nzkarl 2011-06-29 19:55:14