Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Resolve "A specified Include path is not valid"?

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?

like image 881
MisterJames Avatar asked Apr 06 '12 01:04

MisterJames


1 Answers

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.

like image 167
SLaks Avatar answered Nov 13 '22 06:11

SLaks