I want to create a list of Items with parent and children. I have already prepared the data in a sqlite file:
So I want to read this data (I can read data like var subjectnames = await db.SubjectNames.ToListAsync();
) from the database and create a nested list based on being a parent and a child.Each item may have one or more children and the number is unknown.
this is my class:
public class SubjectName
{
public int Id { get; set; }
public long SubjectId { get; set; }
public string Name { get; set; }
public long ParentId { get; set; }
}
public class ExplorerItem : Observable
{
public enum ExplorerItemType { Folder, File, CheckMark };
public string Name { get; set; }
public ExplorerItem Parent { get; set; }
public ExplorerItemType Type { get; set; }
private ObservableCollection<ExplorerItem> m_children;
public ObservableCollection<ExplorerItem> Children
{
get
{
if (m_children == null)
{
m_children = new ObservableCollection<ExplorerItem>();
}
return m_children;
}
set
{
m_children = value;
}
}
private bool m_isExpanded;
public bool IsExpanded
{
get { return m_isExpanded; }
set { Set(ref m_isExpanded, value); }
}
}
and i have a ObservableCollection of ExplorerItem:
var list = new ObservableCollection<ExplorerItem>();
That all data must be added to it
Once the data is completed, the list should be displayed as follows in TreeView
The problem is that I dont Know how to create parent-child relationships and add them to the list. Because their number is not known and they include parent and child nested
CodePudding user response:
If using EF You can change the class and set the configuration as follows:
public class SubjectName
{
public int Id { get; set; }
public long SubjectId { get; set; }
public string Name { get; set; }
public long ParentId { get; set; }
public SubjectName Parent { get; set; }
public ICollection<SubjectName> Chidren{ get; set; }
}
public class SubjectNameConfig : IEntityTypeConfiguration<SubjectName>
{
public void Configure(EntityTypeBuilder<SubjectName> builder)
{
builder.HasKey(e => e.SubjectId);
// Relations
builder.HasOne(d => d.Parent)
.WithMany(p => p.Children)
.HasForeignKey(d => d.ParentId)
.HasPrincipalKey(d => d.SubjectId)
.OnDelete(DeleteBehavior.Restrict);
}
}