【问题标题】:EF Code first invalid column name "CategoryCategoryID"EF 代码第一个无效列名“CategoryCategoryID”
【发布时间】:2011-02-20 15:48:26
【问题描述】:

有一个名为 Northwind 的现有数据库,其中包含一个 Web 表单应用程序。 运行应用程序时出现错误: '无效的列名 CategoryCategoryID'。 任何人帮助我? 提前谢谢!!

Category.cs:

public class Category
{

    public int CategoryID { get; set; }
   // public int ID { get; set; }
    public string CategoryName { get; set; }
    public string Description { get; set; }
    public byte[] Picture { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

Product.cs:

public class Product
{

    public int ProductID { get; set; }
    //public int ID { get; set; }
    public string ProductName { get; set; }
    public Decimal? UnitPrice { get; set; }
    public bool Discontinued{ get; set; }
    public virtual Category Category{ get; set; }
}

Northwind.cs

public class Northwind:   DbContext
{
    public DbSet< Product  > Products { get; set; }
    public DbSet< Category > Categorys{ get; set; }
}

Products.aspx

protected void Page_Load(object sender, EventArgs e)
{
    Northwind northwind = new Northwind();

    var products = from p in northwind.Products
    where p.Discontinued == false
    select p;

    GridView1.DataSource = products.ToList();
    GridView1.DataBind();
}

【问题讨论】:

  • 你为什么评论 Id?可能架构不匹配

标签: entity-framework ef-code-first


【解决方案1】:

解决此问题的一种方法是将新的 FK 属性添加到您的 Product 实体:

public class Product
{
    public int ProductID { get; set; }        
    public string ProductName { get; set; }
    public Decimal? UnitPrice { get; set; }
    public bool Discontinued { get; set; }
    [ForeignKey("Category")]
    public int CategoryId { get; set; }

    public virtual Category Category { get; set; }
}

【讨论】:

  • ForeignKey 在 System.ComponentModel.DataAnnotations 中;命名空间,也可以放在[ForeignKey("Category")] public virtual Category Category { get;放; }
  • 让它成为可选的怎么样?
  • @Morteza Manani 如果我们只有 Products 类中的导航属性,使用 FluentAPI 怎么能做到这一点?
猜你喜欢
  • 1970-01-01
  • 2014-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-16
  • 1970-01-01
  • 2016-01-24
  • 1970-01-01
相关资源
最近更新 更多