问题描述
|
我正在尝试先使用代码将MVC 3与EF 4.1结合使用,并遵循Scott Guthries教程http://weblogs.asp.net/scottgu/archive/2011/05/05/ef-code-first-and-data使用asp-net-mvc-3-tools-update.aspx进行脚手架安装。
我遇到的问题是,当我创建产品控制器和相关的脚手架视图时,在任何视图中都没有创建“类别”列(“编辑”,“创建”, \“ index \”等),则应根据教程创建。
我已经跟踪了为什么不显示该列的原因是由于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工具更新。
我确定我已按照所有步骤进行...
我要去哪里/我想念什么?
解决方法
我相信它确实可以按照本教程中的描述进行工作-我现在刚刚完成了该教程并获得了预期的结果(它确实架起了“类别”列和下拉列表)。
关于为什么它在您的情况下不起作用的最好猜测是,您可能错过了
Product
类中的CategoryID
属性,或者您还称其为其他名称。为了使脚手架检测FK关系,您的实体必须同时具有“导航”属性(在这种情况下为,4ѭ,类型为“ 4”)和“外键”属性(在本例中)类型为int
的CategoryID
)-如果没有,则不会推断出该关系,因此您不会获得该下拉列表。
如果有帮助,这里是您可以复制并粘贴到项目中的模型类的完整代码:
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; }
}
在使用“添加控制器”窗口之前,请记住先编译代码,否则将不会意识到您已经更改了代码。