我有一个自引用表,我需要将日期从表绑定到树视图用户控件。我使用BuildThree()方法来获取子项。我的问题是如何使用我的View模型
获取父级,直到达到根父级我的实体:
public partial class Category
{
public Category()
{
this.children = new HashSet<Category>();
}
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public Nullable<int> ParentCategoryId { get; set; }
public virtual ICollection<Category> children { get; set; }
public virtual Category Parent { get; set; }
}
我的观点模型:
public class TreeViewModel
{
public TreeViewModel()
{
this.children = new HashSet<TreeViewModel>();
}
public int id { get; set; }
public string text { get; set; }
public virtual TreeViewModel MyParent { get; set; }
public virtual IEnumerable<TreeViewModel> children { get; set; }
}
这是我用来生孩子的方法
public IEnumerable<TreeViewModel> BuildThree(IEnumerable<Category> categories, int? parentCategoryId = null)
{
if (categories == null)
return null;
var result = categories.Select(c => new TreeViewModel()
{
id = c.CategoryId,
text = c.CategoryName,
children = BuildThree(c.children, c.CategoryId)
});
return result;
}
Database1Entities db = new Database1Entities();
var category = db.Categories.Find(id);
TreeViewModel vm = new TreeViewModel();
vm.id = category.CategoryId;
vm.text = category.CategoryName;
vm.children = BuildThree(category.children);
答案 0 :(得分:0)
如果您只想找到填充MyParent
属性的方法,那么必须对BuildThree
方法进行少量更改。
public IEnumerable<TreeViewModel> BuildThree(IEnumerable<Category> categories, TreeViewModel parentCategory)
{
if (categories == null)
return null;
var result = new List<TreeViewModel>();
foreach (var category in categories)
{
var treeViewModel = new TreeViewModel();
treeViewModel.Id = category.CategoryId,
treeViewModel.Text = category.CategoryName,
treeViewModel.MyParent = parentCategory;
treeViewModel.Children= BuildThree(category.children,treeViewModel);
result.Add(treeViewModel);
}
return result;
}