Entity framework 4.1 将EF中的代码先用于现有数据库时出错

Entity framework 4.1 将EF中的代码先用于现有数据库时出错,entity-framework-4.1,code-first,Entity Framework 4.1,Code First,我一步一步地遵循教程,但出现以下错误: 无效的列名类别ID 以下是代码摘录: public class Product { public int ProductID { get; set; } public string ProductName { get; set; } public decimal? UnitPrice { get; set; } public bool Discontinued { get; set; } public virtua

我一步一步地遵循教程,但出现以下错误:

无效的列名类别ID

以下是代码摘录:

public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public decimal? UnitPrice { get; set; }
    public bool Discontinued { get; set; }

    public virtual Category Category { get; set; } 
}

public class Category
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
    public string Description { get; set; }
    public byte[] Picture { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}
公共类产品
{
public int ProductID{get;set;}
公共字符串ProductName{get;set;}
公共十进制?单价{get;set;}
公共布尔已中断{get;set;}
公共虚拟类别{get;set;}
}
公共类类别
{
public int CategoryID{get;set;}
公共字符串CategoryName{get;set;}
公共字符串说明{get;set;}
公共字节[]图片{get;set;}
公共虚拟ICollection产品{get;set;}
}
为什么会发生这种情况


编辑-我可以通过将
公共int-CategoryID
包含在产品类中来完成这项工作,但不知道细节。

您需要让EF知道产品。类别与Category.Products相反。我不知道为什么斯科特格大学的博文中没有显示这一点

在DbContext子类中,您需要的代码如下所示:

protected override void OnModelCreating(ModelBuilder modelBuilder {)
  modelBuilder.Entity<Product>().HasOne(p => p.Category).WithMany(c => c.Products);
}
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder{)
modelBuilder.Entity().HasOne(p=>p.Category).WithMany(c=>c.Products);
}