如何解决“指定的包含路径无效”? [英] How Do I Resolve "A specified Include path is not valid"?

查看:1492
本文介绍了如何解决“指定的包含路径无效”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当基本的父子关系设置。最终的结果是,我希望能够通过ASP.NET MVC WebAPI将生成的表返回为JSON。我正在使用Entity Framework 5.0 beta 2.



我可以用一个简单的例子演示我遇到的错误。给出类别类别产品与相应的数据上下文:

  public class Category 
{
public int CategoryId {get;组; }
public string标题{get;组; }

public virtual IEnumerable< Product>产品{get;组; }
}

public class Product
{
public int ProductId {get;组; }
public string标题{get;组; }

public virtual Category Category {get;组; }
public virtual int CategoryId {get;组; }
}

public class ProductDataContext:DbContext
{
public DbSet< Category>分类{get;组; }
public DbSet< Product>产品{get;组; }
}

当我尝试运行包含产品的查询时,我得到以下内容错误:

 指定的包含路径无效。 EntityType'FooAndBar.Category'
不声明具有名称Products的导航属性。

要获取的语句非常简单:

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

正确的方法是设置列和/或查询,以便产品包含在 Categories

解决方案

儿童收藏属性必须被声明为 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.

这篇关于如何解决“指定的包含路径无效”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆