c# - Entity Framework 自连接

标签 c# entity-framework

<分区>

我使用 Entity Framework 6 和 Code First,我有一个具有以下结构的表:

public class Item
{
    [Key]
    public int ItemId { get; set; }

    [Required]
    [MaxLength(255)]
    public string Name { get; set; }}

    public Item Parent { get; set; }
    public virtual List<Item> Children { get; set; }       
}

我想知道是否有可能对数据库进行一次查询/访问,所有 Items 穿过我的树直到根,提供一个 itemId 作为参数.

例如,给我从 ItemId 55 到找不到父项的所有父项。

最佳答案

您无法使用任何合理的代码让所有 parent 一次旅行。

但是你可以这样做:https://stackoverflow.com/a/11565855/304832

通过稍微修改您的实体,您可以添加 2 个派生集合:

public class Item
{
    [Key]
    public int ItemId { get; set; }

    [Required]
    [MaxLength(255)]
    public string Name { get; set; }}

    public virtual Item Parent { get; set; } // be sure to make this virtual
    public virtual List<Item> Children { get; set; }

    public virtual ICollection<ItemNode> Ancestors { get; set; }
    public virtual ICollection<ItemNode> Offspring { get; set; }
}

你确实需要引入一个新的实体来完成这项工作,它看起来像这样:

public class ItemNode
{
    public int AncestorId { get; set; }
    public virtual Item Ancestor { get; set; }

    public int OffspringId { get; set; }
    public virtual Item Offspring { get; set; }

    public int Separation { get; set; } // optional
}

现在,如果你想

all parents from ItemId 55 until no parent is found

...你可以这样做:

IEnumerable<Item> allParentsFrom55 = dbContext.Set<Item>()
    .Find(55).Ancestors.Select(x => x.Ancestor);

关于c# - Entity Framework 自连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27492539/

相关文章:

c# - CLR 工作线程和工作线程有什么区别?

c# - 将 mysql 数据库中的字符串日期与 Entity Framework c# 进行比较

c# - 如何使用扩展方法加入 .NET Entity Framework 中的多个列?

entity-framework - 为什么我会得到一个带有 Entity Framework 代码优先外键属性的额外外键列?

entity-framework - System.OutOfMemoryException 使用 Entity Framework ?

entity-framework - Code First - 在一对多关系中将级联规则设置为 "Set Null"

c# - 使用 Json.Net 反序列化,将子对象反序列化为包含 json 的字符串/类似字符串?

c# - 转换方法。 "The specified method on the type cannot be translated into a LINQ to Entities store expression"

c# - 该类型不具有 EdmEntityTypeAttribute 属性,但包含在具有 EdmSchemaAttribute 属性的程序集中

c# - 图像缩放后我如何更新滚动查看器?