ASP.NET MVC中的递归

Dee*_*eej 1 c# asp.net asp.net-mvc recursion cakephp

来自CakePHP背景,现在正在使用ASP.NET,我很难找到模型中的等效功能,该功能在CakePHP中称为Recursion.

例如,在博客应用中,帖子有作者.在Cake中,如果我只想检索Post,而不是相关实体,我将递归设置为0,模型只返回该实体.如果我将它设置为1,它也会带回第一级相关实体,因此作者姓名等.

我正在寻找ASP.NET模型中的类似函数,但似乎找不到类似的东西,并继续在我的API上获取引用循环,例如Post,Author,Author's Posts,Post's Authors等等.

如何限制ASP.NET中的递归深度?

SBi*_*are 5

在实体框架中,此概念称为"预先加载".

预先加载是一种过程,其中对一种类型的实体的查询也将相关实体作为查询的一部分加载.通过使用Include方法实现预先加载.例如,下面的查询将加载博客以及与每个博客相关的所有帖子.

using (var context = new BloggingContext()) 
{ 
    // Load all blogs and related posts 
    var blogs1 = context.Blogs 
                          .Include(b => b.Posts) 
                          .ToList(); 

    // Load one blogs and its related posts 
    var blog1 = context.Blogs 
                        .Where(b => b.Name == "ADO.NET Blog") 
                        .Include(b => b.Posts) 
                        .FirstOrDefault(); 

    // Load all blogs and related posts  
    // using a string to specify the relationship 
    var blogs2 = context.Blogs 
                          .Include("Posts") 
                          .ToList(); 

    // Load one blog and its related posts  
    // using a string to specify the relationship 
    var blog2 = context.Blogs 
                        .Where(b => b.Name == "ADO.NET Blog") 
                        .Include("Posts") 
                        .FirstOrDefault(); 
}
Run Code Online (Sandbox Code Playgroud)

请注意,Include是System.Data.Entity命名空间中的扩展方法,因此请确保使用该命名空间.

有关更多信息,请参阅此链接:

https://msdn.microsoft.com/en-us/data/jj574232.aspx