Entity-framework – How Do I Resolve “A specified Include path is not valid”

ef-code-first, entity-framework

I have a parent-child relationship setup that is fairly basic. The end result is that I want to be able to return the resulting tables as JSON through ASP.NET MVC WebAPI. I am using Entity Framework 5.0 beta 2.

I can demonstrate the error I'm running into with a simple example. Given the classes Category and Product with the corresponding data context:

public class Category{    public int CategoryId { get; set; }    public string Title { get; set; }    public virtual IEnumerable<Product> Products { get; set; }}public class Product{    public int ProductId { get; set; }    public string Title { get; set; }    public virtual Category Category { get; set; }    public virtual int CategoryId { get; set; }}public class ProductDataContext : DbContext{    public DbSet<Category> Categories { get; set; }    public DbSet<Product> Products { get; set; }}

When I try to run a query that includes the products I get the following error:

A specified Include path is not valid. The EntityType 'FooAndBar.Category' does not declare a navigation property with the name 'Products'.

The statement to fetch is pretty straightforward:

var everything = dc.Categories            .Include(c => c.Products);

What is the correct way to setup the columns and/or the query so that the Products are included with the Categories?

Best Solution

Child collection properties must be declared as anICollection<T>, not anIEnumerable<T>.

Also, you do not need to explicitly add a CategoryId field to the child class; EF will create that automatically in the database.