实体框架自己加入 [英] Entity Framework Self Join
问题描述
public class Item
{
[Key]
public int ItemId {get;组;
[必需]
[MaxLength(255)]
public string Name {get;组; }}
public Item Parent {get;组; }
public virtual List< Item>孩子{get;组; }
}
我想知道是否可以获得单个查询/旅行数据库,我的树上的所有项目
直到根,提供一个 itemId
作为参数。
例如,给我所有的父母从 ItemId
55,直到找不到父母。
您无法使用任何合理的代码让所有家长一次性使用。
但是,您可以执行以下操作: https://stackoverflow.com/a/11565855/304832
通过修改您的实体,您可以添加2个派生集合:
public class Item
{
[Key]
public int ItemId {get;组;
[必需]
[MaxLength(255)]
public string Name {get;组; }}
public virtual Item Parent {get;组; } //确保使这个虚拟
public virtual List< Item>孩子{get;组; }
public virtual ICollection< ItemNode>祖先{get;组; }
public virtual ICollection< ItemNode>后代{get;组; }
}
你确实需要引入一个新的实体,看起来像这样:
public class ItemNode
{
public int AncestorId {get;组; }
public virtual Item Ancestor {get;组; }
public int OffspringId {get;组; }
public virtual Item后代{get;组; }
public int Separation {get;组; } //可选
}
现在,如果你想要
来自ItemId 55的所有父母,直到找不到父母
你可以这样做:
IEnumerable< Item> allParentsFrom55 = dbContext.Set< Item>()
.Find(55).Ancestors.Select(x => x.Ancestor);
I am using Entity Framework 6 with Code First, and I have a table with the following structure:
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; }
}
I would like to know if it's possible to get on a single query/trip to database, all Items
across my tree until the root, supplying a itemId
as argument.
e.g Give me all parents from ItemId
55 until no parent is found.
You cannot get all parents in one trip using any sane code.
However you can do something like this: https://stackoverflow.com/a/11565855/304832
By modifying your entity a bit, you can add 2 derived collections:
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; }
}
You do need to introduce a new entity to make this work though, which looks like this:
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
}
Now, if you want
all parents from ItemId 55 until no parent is found
...you can do something like this:
IEnumerable<Item> allParentsFrom55 = dbContext.Set<Item>()
.Find(55).Ancestors.Select(x => x.Ancestor);
这篇关于实体框架自己加入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!