为什么在.Join()之后调用.Include()不起作用?

时间:2015-08-21 15:36:15

标签: c# linq-to-entities entity-framework-core

我有一个不太理想的数据库结构,但是我把它编码成EF就像这样:

[Table("Item")]
public class Item
{
    [Key] public int Id { get; set; }
    public int CategoryId { get; set; }
    public int ItemTypeId { get; set; }  // An ItemTypeId of 1 means this row refers to an Article
    public int ItemId { get; set; }      // this refers to the Article primary key
}

[Table("Article")]
public class Article
{
    [Key] public int Id { get; set; }
    ...
    public virtual ICollection<SubArticle> SubArticles { get; set; }
}

[Table("SubArticle")]
public class SubArticle
{
    ...
    public int ArticleId { get; set; }
}

modelBuilder.Entity<Article>().Collection(_ => _.SubArticles).InverseReference(_ => _.Article).ForeignKey(_ => _.ArticleId);

我想要做的是获取属于特定类别的所有文章(以及相应的子文章)。我有这个查询正在运行:

var result = await Context.Set<Item>()
       .Where(i => i.CategoryId == 200)
       .Where(i => i.ItemTypeId == 1)
       .Join(
           Context.Set<Article>().Include(a => a.SubArticles),
           i => i.ItemId,
           a => a.Id,
           (i,a) => a)
       .ToListAsync();

result.SubArticles.First(); // works

我的问题是为什么这个查询不起作用:

var result = await Context.Set<Item>()
       .Where(i => i.CategoryId == 200)
       .Where(i => i.ItemTypeId == 1)
       .Join(
           Context.Set<Article>(),
           i => i.ItemId,
           a => a.Id,
           (i,a) => a)
       .Include(a => a.SubArticles)
       .ToListAsync();

result.SubArticles.First(); // error: result.SubArticles is null

0 个答案:

没有答案