目前我有一个递归模型(其属性之一属于同一类型)。
例如:
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; }
}
因为我认为 Entity Framework 会自动假设 Parent 链接到 ParentID,但这不起作用。
好的,这是我的所有代码: Controller 方法如下:
public ActionResult Create()
{
var pages = _db.Pages;
ViewBag.Pages = new SelectList(pages,"ID","Description");
return View();
}
在 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; }
当我进入“创建 View ”时。我获得了所有页面的列表,但是当我创建它们时,新页面的 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; }
}
关于c# - ASP.NET MVC "strong"关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7702669/