Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code first invalid column name "CategoryCategoryID"

There is a existing database named Northwind with a webform application. when running the application raise up a error: 'invalid column name CategoryCategoryID'. any one help me?. thanks in advance!!

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();
}
like image 700
user441222 Avatar asked Feb 20 '11 15:02

user441222


1 Answers

One way to solve this is to add a new FK property to your Product entity:

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; }
}
like image 75
Morteza Manavi Avatar answered Nov 04 '22 18:11

Morteza Manavi