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

馋奶兔 提交于 2019-12-08 16:25:35

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/10038037/how-do-i-resolve-a-specified-include-path-is-not-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!