13

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();
}
1
  • 1
    why you commented Id? probably schema mis match
    – indiPy
    Feb 20, 2011 at 18:15

1 Answer 1

13

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; }
}
3
  • ForeignKey is in the System.ComponentModel.DataAnnotations; namespace and can also be put on the [ForeignKey("Category")] public virtual Category Category { get; set; } Apr 27, 2012 at 20:02
  • How about making it optional? Dec 11, 2012 at 10:02
  • @Morteza Manani how could this be done if we only had the navigation property in the Products class, using FluentAPI?
    – Odys
    Dec 1, 2013 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.