实体框架核心渴望加载然后包含在集合中

All*_*olo 25 c# entity-framework entity-framework-core

我在执行查询时要包含三个模型.

这是场景.

public class Sale
{
     public int Id { get; set; }
     public List<SaleNote> SaleNotes { get; set; }
}

public class SaleNote
{
    public int Id { get; set; }
    public User User { get; set; }
}

public class User 
{
    public int Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我可以像这样急切加载SaleNotes ......

_dbContext.Sale.Include(s => s.SaleNotes);
Run Code Online (Sandbox Code Playgroud)

但是,尝试使用ThenInclude从SaleNote急切加载User模型是一项挑战,因为它是一个集合.我找不到任何关于如何加载此方案的示例.有人可以提供下面的代码ThenInclude来加载集合中每个项目的用户.

_dbContext.Sale.Include(s => s.SaleNotes).ThenInclude(...);
Run Code Online (Sandbox Code Playgroud)

oct*_*ccl 41

这与SaleNotes集合导航属性无关.对于引用和集合,它应该是相同的:

_dbContext.Sale.Include(s => s.SaleNotes).ThenInclude(sn=>sn.User);
Run Code Online (Sandbox Code Playgroud)

但据我所知,EF7还支持使用Select扩展方法的旧的多级Include语法:

_dbContext.Sale.Include(s => s.SaleNotes.Select(sn=>sn.User));
Run Code Online (Sandbox Code Playgroud)

  • 谢谢您的回答.我实际上发现虽然User没有出现在intellisense中,但我添加了sn.User,构建了我的解决方案,然后它运行了!intellisense将lambda表达式中的SaleNotes"sn"视为一个集合,因此它没有显示User类的各个属性. (35认同)
  • @AllenRufolo有两个重载,一个给你整个列表(第一个,默认一个),另一个给你列表中的每个项目(第二个) - 所以,如果你只是在intellisense中做"向下箭头" ,你会看到预期的intellisense选项.我自己也有同样的困惑:-) (4认同)
  • 艾伦,你是绝对正确的.我在VS 2017 15.4上使用EF Core 2.0并且intelliesense无法正常工作,但是如果您只需输入您需要的属性名称,那就没问题了.这帮了我一堆. (3认同)
  • @AllenRufolo 感谢您关于未在智能感知中显示的评论。这是疯狂的错误!你为我节省了很多精力!我从来没有想到智能感知在这里可能不起作用。 (2认同)

Ban*_*ito 5

作为参考,最新版本的EF Core(1.1.0)也支持此方案的显式加载。像这样

using (var _dbContext = new DbContext())
{
    var sale = _dbContext.Sale
        .Single(s => s.Id == 1);

    _dbContext.Entry(sale)
        .Collection(n => n.SalesNotes)
        .Load();

    _dbContext.Entry(sale)
        .Reference(u => u.User)
        .Load();
}
Run Code Online (Sandbox Code Playgroud)