1

我使用实体框架从数据库中获取一条记录。它有嵌套导航属性。

  public partial class Comment
{
    public Comment()
    {
        this.Comments1 = new HashSet<Comment>();
    }

    public int CommentId { get; set; }
    public Nullable<int> ParentId { get; set; }
    public string Title { get; set; }

    public virtual ICollection<Comment> Comments1 { get; set; }
    public virtual Comment Comment1 { get; set; }
}

ID 和父 ID 之间的关系。我的导航是 Comments1 。现在我选择一个有 5 个嵌套导航的记录。我希望使用 C# 代码在我的控制器中仅限制为 3 个嵌套导航。如何创建递归方法并将嵌套导航限制为 3 级?

4

1 回答 1

1

不幸的是,EF 中不存在该功能。您可以做的是禁用延迟加载:

public class YourContext : DbContext 
{ 
    public YourContext() 
    { 
        this.Configuration.LazyLoadingEnabled = false; 
    } 
}

然后使用Include扩展方法作为查询的一部分来加载您需要的级别:

var query=context.Comments.Include(c=>Comments1.Select(c1=>c1.Comments1))...;

我认为另一种解决方案可能是使用Automapper,如果我的想法没有让我失望,我认为您可以使用MaxDepth自引用属性中的方法来指定要加载的级别:

 configuration.CreateMap<Comment, CommentViewModel>()
              .ForMember(dest => dest.Comments, opt => opt.MapFrom(src => src.Comments1).MaxDepth(3)...; 
于 2016-04-28T19:25:02.690 回答