gpt4 book ai didi

c# - Entity Framework 复杂的树结构

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:40 25 4
gpt4 key购买 nike

我有一个复杂的树结构,我正在尝试使用代码优先方法创建它。主要思想是一个有 child 集合的类(class)。每个子级可以是类本身的相同类型(Folder)或某个其他类(File)。这可以通过从同一基本接口(interface)派生的 2 个类在编程语言中实现。这是我更愿意代表我的类(class)的方式:

public interface IBasicTreeItem
{
string DisplayName { get; }
}

public class Folder : IBasicTreeItem
{
public int Id { get; set; }
public string DisplayName { get; set; }
// This collection should be able to hold both Folder and File types
public virtual ICollection<IBasicTreeItem> Children { get; set; }

// Following 2 properties represent the parent folder
// The file may not have a parent - in this case, it will be positioned in the root
public int? FolderId { get; set; }
public Folder ParentFolder { get; set; }
}

public class File : IBasicTreeItem
{
public int Id { get; set; }
public string DisplayName { get; set; }

// Following 2 properties represent the parent folder
// The file may not have a parent - in this case, it will be positioned in the root
public int? FolderId { get; set; }
public Folder ParentFolder { get; set; }
}

问题是这不适用于数据库,至少不是以这种直接的方式,这就是我需要一些帮助来弄清楚如何正确构建我的类的地方。

我尝试过的另一件事是首先创建数据库并从中生成 C# 对象(File 表具有指向 Folder 表的外键,等等Folder 表本身) - 它导致了一些错误,但我可以看到它建议的基本思想 - Folder 类中的两个集合,每个儿子一个 -它可以容纳的类型(这不是我希望的解决方案,因为我必须实现某种中间集合,它必须将两个集合联合起来)。

最佳答案

您可以将 Folder 的文件和文件夹分成两个不同的集合 - 两个表,并实现 Folder 类的一些未映射属性以返回您的文件和文件夹转换为IBasicTreeItem

public interface IBasicTreeItem
{
int Id { get; set; }
string DisplayName { get; set; }
int? FolderId { get; set; }
}

public class BasicTreeItem : IBasicTreeItem
{
public int Id { get; set; }
public string DisplayName { get; set; }
public int? FolderId { get; set; }
}

public class Folder : BasicTreeItem
{
public Folder ParentFolder { get; set; }
public virtual ICollection<Folder> Folders { get; set; }
public virtual ICollection<File> Files { get; set; }

[NotMapped]
public ICollection<IBasicTreeItem> Content { get {
return Files.Concat(Folders).Cast<IBasicTreeItem>();
} }
}

public class File : BasicTreeItem
{
public Folder ParentFolder { get; set; }
}

关于c# - Entity Framework 复杂的树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25837561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com