使用 Lambda/Linq EF C# 从 3 个模型中获取值,其中 1 个模型是主根

今天是个好日子,


我正在尝试使用 EF 从数据库中检索数据。


我有 3 个这 3 个样本模型


public class Info { 

    [Key] public int InfoId {get;set;}

    public string infoName {get;set;}


    public ICollection<SubInfo> SubInfo {get;set;}

 }


 public class SubInfo { 

    [Key] public int SubInfoId {get;set;}

    public string subInfoName {get;set;}


    public Info Info {get;set}

    public int InfoId {get;set;}

    public ICollection<SubSubInfo> SubSubInfo {get;set;}

 }


 public class SubSubInfo { 

    [Key] public int SubSubInfoId {get;set;}

    public string subInfoName {get;set;}


    public SubInfo SubInfo {get;set}

    public int SubInfoId {get;set;}

 }

关于explain的模型:Info是main,SubInfo是main InfoSubSubInfo的sub,是sub info details的sub。


到目前为止,我使用这个类似的代码来检索数据,它工作正常


var info = context.Info.Include(x=>x.SubInfo).ToList();

但问题是,结果中的 SubSubInfo 是空的。


我试过这个:var info = context.Info.Include(x=>x.SubInfo.Select((y=>y.SubSubInfo)));但我收到一个错误,上面写着:InvalidOperationException: The Include property lambda expression 'x => ...


噜噜哒
浏览 253回答 2
2回答

长风秋雁

您想要实现的目标可以通过Eager Loading轻松完成,可以在此处或此处阅读有关它的更多信息。你所得到的错误是,你不能合并LINQ与原始SQL(Include和Select你的情况)。您想加载通过Include和ThenInclude方法实现的多个级别。一个例子是using (var context = new BloggingContext()){&nbsp; &nbsp; var blogs = context.Blogs&nbsp; &nbsp; &nbsp; &nbsp; .Include(blog => blog.Posts)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ThenInclude(post => post.Author)&nbsp; &nbsp; &nbsp; &nbsp; .ToList();}对于您的上下文,它将是:var info = context.Info.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Include(subInfo => subInfo.SubInfo).&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ThenInclude(subSubInfo => subSubInfo.SubSubInfo).&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ToList();whereSubInfo和SubSubInfo是模型的导航属性。还要考虑到您必须提及您使用的是.NET Core还是.NET Framework,因为.NET Core不支持延迟加载。但我看到@AliJP 已经回答了你的问题。编辑结束如果您想了解有关此主题的更多信息,请尝试阅读有关Eager Loading和Lazy Loading 的内容。

繁星淼淼

当您使用多个包含时,您必须首先包含您的第一个级别。在您的示例中:var&nbsp;info&nbsp;=&nbsp;context.Info.Include(x=>&nbsp;x.SubInfo) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Include(x=>&nbsp;x.SubInfo.Select(y=>&nbsp;y.SubSubInfo&nbsp;));如果您使用 EF Core,也可以使用 ThenInclude()。有关详细信息,请参阅下面的链接http://entityframework.net/include-multiple-levels
打开App,查看更多内容
随时随地看视频慕课网APP