且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何解决“指定的包含路径无效”?

更新时间:2022-10-31 17:55:19

儿童收藏属性必须被声明为 ICollection< T> ,而不是 IEnumerable< T>



此外,您不需要向子类显式添加 CategoryId 字段; EF将在数据库中自动创建。


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?

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.