目前,我有一个递归的模型(其属性之一是同一类型)。

例如:

public class Page
{
  public int ID { get; set; }
  public string Description{ get; set; }
  public int ParentID  {get; set; }

}


现在,当我想访问某人的父母时,我将必须获取ParentID,查询数据库并找到页面。我想要的是我可以执行以下操作:

Page page = _db.GetFirstPage();
Page pagesParent = page.Parent;


我该如何实现?我尝试了以下方法:

public class Page
{
  public int ID { get; set; }
  public string Description{ get; set; }
  public int ParentID  {get; set; }
  public Page Parent { get; set; }

}


因为我认为实体框架会自动假设Parent已链接到parentID,但这是行不通的。



好了,这是我所有的代码:
控制器方法如下:

public ActionResult Create()
    {
        var pages = _db.Pages;
        ViewBag.Pages = new SelectList(pages,"ID","Description");
        return View();
    }


在视图中:

    <div class="editor-label">
        @Html.LabelFor(model => model.ParentID)
    </div>
    <div class="editor-field">
        @Html.DropDownList("Pages", String.Empty)
        @Html.ValidationMessageFor(model => model.ParentID)
    </div>


该模型:

    public int ID { get; set; }
    public string Description { get; set; }
    public string Body { get; set; }

    public int? ParentID { get; set; }
    public virtual Page Parent { get; set; }


当我转到创建视图时。我得到所有页面的列表,但是当我创建它们时,新页面的Parent属性为null。

最佳答案

您需要使ParentID属性可为空,因为每个页面都没有父级。同时将Parent属性设置为虚拟,以允许延迟加载。

public class Page
{
  public int ID { get; set; }
  public string Description{ get; set; }

  public int? ParentID  {get; set; }
  public virtual Page Parent { get; set; }

}

10-02 02:21
查看更多