在现有数据库中使用 EF 中的代码优先时出错
我遵循 逐步使用 EF“Code First”与现有数据库教程,但出现以下错误:
列名 Category_CategoryID 无效
以下是代码摘录:
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 CategoryID
来完成这项工作,但不知道详细信息。
I followed Using EF “Code First” with an Existing Database tutorial step by step but getting the following Error :
Invalid column name Category_CategoryID
Following is the code Excerpt :
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; }
}
Why does this happen.
EDIT - I am able to make this work by including public int CategoryID
in Product Class but dont know the details.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要让 EF 知道 Products.Category 是 Category.Products 的逆。我不知道为什么 ScottGu 的博客文章中没有显示这一点。
您需要的代码在 DbContext 子类中如下所示:
You need to let EF know that Products.Category is the inverse of Category.Products. I'm not sure why that's not shown in ScottGu's blog post.
The code you need would be something like this in your DbContext subclass: