我正在尝试使用带有EF4.1的MVC3,首先使用代码,并遵循Scott 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。
我遇到的问题是,当我创建products控制器和相关的脚手架视图时,没有在任何视图中创建“类别”列(“编辑”、“创建”、“索引”等),根据教程,这些列应该被创建。
我已经追踪到列没有显示的原因是因为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、EF4.1和教程中提到的MVC3工具更新。我确定我已经遵循了所有的步骤。
我哪里做错了/我遗漏了什么?
发布于 2011-06-29 20:51:50
我相信它确实像教程中描述的那样工作--我现在只是浏览了一下教程,得到了预期的结果(它确实搭建了一个"Category“列和下拉列表)。
我最好的猜测是,为什么它在您的例子中不起作用,可能是您在Product类中遗漏了CategoryID属性,或者您使用了其他名称。为了让脚手架检测FK关系,你的实体必须同时有一个“导航”属性(在本例中是Category类型的Category )和一个“外键”属性(在本例中是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; }
}记得在使用"Add Controller“窗口之前编译你的代码,否则它不会意识到你已经修改了代码。
https://stackoverflow.com/questions/6319802
复制相似问题