【问题标题】:Entity Framework self referencing - Parent-Child实体框架自引用 - 父子
【发布时间】:2017-01-14 15:20:47
【问题描述】:

我有一个自引用表,我需要将表中的日期绑定到树视图。亲子。我的问题是如何使用匿名类型的实体框架从该表中获取树视图

有些是这样的:

var tree = db.Categories.Select(g => new

    {
        id = g.CategoryId,

        text = g.CategoryName,

        children = g.children.Select(w => new
        {

            id = w.CategoryId,
            parent = w.ParentCategoryId,
            text = w.CategoryName,


        }).ToList(),


    }
         ).ToList();

代码如下:

 public partial class Category
    {

        public Category()
        {
            this.children = new HashSet<Category>();
        }

        public int CategoryId { get; set; }
        public string CategoryName { get; set; }
        public Nullable<int> ParentCategoryId { get; set; }

        public virtual ICollection<Category> children { get; set; }
        public virtual Category Parent { get; set; }
    }

【问题讨论】:

  • 你已经有了某种三视图,你到底想实现什么?
  • @Elias 我编辑了代码。请再看一遍。非常感谢
  • @J. Pichardo....我编辑了代码。请再看一遍。非常感谢
  • @Tom,看看我的回答

标签: c# sql-server entity-framework


【解决方案1】:

我想为您的目的创建一个类型,而不是使用匿名类型并通过递归方法填充模型。

var three = BuildThree(db.Categories);

public IEnumerable<CategoryVm> BuildThree(IEnumerable<Categories> categories, int? parentCategoryId = null)
{
  if (categories == null)
  return null;
  var result = categories.select(c => new CategoryVm()
    { 
         id = c.CategoryId,
         text = c.CategoryName,
         parent = parentCategoryId, 
         children = BuildThree(c.children, c.CategoryId) 
    }
    return result;
 }

此解决方案有一个缺点 - 每次调用导航属性(子项)时,您都会向数据库发出请求。如果您想在一个请求中完成它并且您只有一层嵌套类别,那么.Include(c =&gt; c.Children) 就足够了,否则您必须选择以下选项之一:

  1. 编写一个公用表表达式(CTE)查询,放到视图或存储过程中,并通过EF映射。 EF的作用其实并不大,因为最棘手的部分是SQL查询

  2. 特别是针对这种目的,Microsoft SQL Server 有hierarchyid,但 EF 不支持它。但是有一些解决方法:Entity Framework HierarchyId Workarounds

  3. 您可以将rootId 之类的内容添加到Comment 实体,此时每个子回放都会有一个指向根评论的链接。之后,您可以在一个 sql 查询中将所有层次结构加载到内存并手动映射。鉴于数据库是瓶颈,它会更快地为每个层次结构级别进行新查询。

【讨论】:

猜你喜欢
  • 2012-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 2017-07-22
  • 2016-10-19
相关资源
最近更新 更多