12

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?

MisterJames
  • 3,306
  • 1
  • 30
  • 48

1 Answers1

38

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • I have posted a related question here if you care to take a stab: http://stackoverflow.com/questions/10038628/error-when-serializing-ef-code-first-5-0-data-in-webapi-controller Thanks for your help otherwise! – MisterJames Apr 06 '12 at 03:04
  • Quick and accurate answer. Thx! – Gonzalo Méndez Sep 25 '15 at 17:45