在现有数据库中使用 EF 中的代码优先时出错

发布于 2024-12-07 13:28:26 字数 921 浏览 4 评论 0原文

我遵循 逐步使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

來不及說愛妳 2024-12-14 13:28:26

您需要让 EF 知道 Products.Category 是 Category.Products 的逆。我不知道为什么 ScottGu 的博客文章中没有显示这一点。

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

protected override void OnModelCreating(ModelBuilder modelBuilder {)
  modelBuilder.Entity<Product>().HasOne(p => p.Category).WithMany(c => c.Products);
}

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:

protected override void OnModelCreating(ModelBuilder modelBuilder {)
  modelBuilder.Entity<Product>().HasOne(p => p.Category).WithMany(c => c.Products);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文