Error using Code-first in EF with an Existing Database
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; }
p开发者_Python百科ublic 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.
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);
}
精彩评论