2016-02-12 193 views
1

我不太清楚我在这里错过了什么。这似乎毫无疑问,但由于某种原因,类总是回来为空,我总是遇到这些问题时使用实体框架。我想弄清楚我做错了什么。产品ID,产品名称和类别ID都有数据,但类别始终为空。我试图撤回产品列表以及与产品关联的类别。实体框架7关系

任何帮助,将不胜感激。

使用臭名昭著的Northwind数据库

[Table("Products")] 
public class Products 
{ 
    [Key] 
    public int ProductID { get; set; } 
    public string ProductName { get; set; } 
    public int CategoryID { get; set; } 
    [ForeignKey("CategoryID")] 
    public virtual Categories Category { get; set; } 
} 

[Table("Categories")] 
public class Categories 
{ 
    [Key] 
    public int CategoryID { get; set; } 
    public string CategoryName { get; set; } 
    public virtual ICollection<Products> Product { get; set; } 
} 

的DbContext(相关代码)

public DbSet<Categories> Categories { get; set; } 
public DbSet<Products> Products { get; set; } 

这就是会返回产品从我的存储库中的代码

public IEnumerable<Products> GetAll() 
{ 
    return _db.Products.AsEnumerable(); 
} 
+1

的路线图,您可以提供使用该查询拉回空类别? – Matthew

+0

@MatthewVerstraete补充说。 – Anonymous

+1

return _db.Products.Include(“Categories”)。AsEnumerable(); –

回答

4

您应该使用扩展方法从EntityFramework.Core中的Microsoft.Data.Entity命名空间的Include()a ssembly。

using Microsoft.Data.Entity; 
    ... 
    return _db.Products.Include(p => p.Category).AsEnumerable(); 

因为EF7不支持相关实体的延迟加载,但它像EF6中实现的一样。因此您需要使用.Include方法加载所有相关的实体,例如也许将来会得到支持。

您可以按照EF7这里https://github.com/aspnet/EntityFramework/wiki/Roadmap