我有一個非常基本的父子關係設置。最終結果是我希望能夠通過ASP.NET MVC WebAPI將結果表作為JSON返回。我正在使用Entity Framework 5.0 beta 2。
我可以用一個簡單的例子來演示我遇到的錯誤。給定Category
和Product
以及相應的數據上下文:
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; }
}
當我嘗試運行包含產品的查詢時,我收到以下錯誤:
A specified Include path is not valid. The EntityType 'FooAndBar.Category'
does not declare a navigation property with the name 'Products'.
要獲取的語句非常簡單:
var everything = dc.Categories
.Include(c => c.Products);
設置列和/或查詢的正確方法是什麼,以便Products
包含在Categories
?
子集合屬性必須聲明為ICollection<T>
,而不是IEnumerable<T>
。
此外,您不需要向子類顯式添加CategoryId
字段; EF將在數據庫中自動創建。