1) 使用您的模型
在父项 ID 和项 ID 之间添加外键(自引用)。
CREATE TABLE [dbo].[26957446_All]([id] [int] NOT NULL,[name] [varchar](50) NOT NULL, [parentid] [int] NULL, CONSTRAINT [PK_26957446_All] PRIMARY KEY CLUSTERED ( [id] ASC )
ALTER TABLE [dbo].[26957446_All] WITH CHECK ADD CONSTRAINT [FK_26957446_Circular] FOREIGN KEY([parentid]) REFERENCES [dbo].[26957446_All] ([id])
ALTER TABLE [dbo].[26957446_All] CHECK CONSTRAINT [FK_26957446_Circular]
生成模型:,注意自引用,名称自动生成,All1 是子代,All2 是父代引用。
var ents = new DynamicCategory.StackOverflowEntities26957446All();
// all root items loop
foreach (var item in ents.C26957446_All.Where(x => x.C26957446_All2 == null))
{
Console.WriteLine("Id: {0} Name: {1}", item.id, item.name);
PrintChildrenRecursively(item);
}
static int i = 1; //level
static void PrintChildrenRecursively (DynamicCategory.C26957446_All item)
{
foreach (var c in item.C26957446_All1)
{
Console.WriteLine("{2} Child Id: {0} Name: {1}", c.id, c.name, new string('\t', i));
if (c.C26957446_All1.Count > 0)
{
i++;
PrintChildrenRecursively(c);
i--;
}
Console.WriteLine();
}
}
输出:
2) 使用不同的数据库组织。将项目和关系分开到单独的表中。将Relationship.Child 和Relationship.Parent 中的外键添加到Items 表中。
CREATE TABLE [dbo].[26957446_Items]([id] [int] NOT NULL, [name] [varchar](50) NOT NULL, CONSTRAINT [PK_26957446_Items] PRIMARY KEY CLUSTERED ([id] ASC))
CREATE TABLE [dbo].[26957446_Relationships](ParentId] [int] NOT NULL, [ChildId] [int] NOT NULL, CONSTRAINT [PK_Relationships] PRIMARY KEY CLUSTERED ([ParentId] ASC, [ChildId] ASC ))
ALTER TABLE [dbo].[26957446_Relationships] WITH CHECK ADD CONSTRAINT [FK_Child] FOREIGN KEY([ChildId]) REFERENCES [dbo].[26957446_Items] ([id])
ALTER TABLE [dbo].[26957446_Relationships] CHECK CONSTRAINT [FK_Child]
ALTER TABLE [dbo].[26957446_Relationships] WITH CHECK ADD CONSTRAINT [FK_Parent] FOREIGN KEY([ParentId]) REFERENCES [dbo].[26957446_Items] ([id])
ALTER TABLE [dbo].[26957446_Relationships] CHECK CONSTRAINT [FK_Parent]
生成的 EF:,请注意仅使用自下而上和自上而下的引用生成的类。输出相同,代码非常相似,除了:item.ItemChildren 是子项,根项访问权限是:
var ents = new DynamicCategory.StackOverflowEntities26957446();
ents.C26957446_Items.Where (x=>x.ItemParents.Count==0)