[英]Hierarchical data representation using entity framework in MVC
嘿,我正在嘗試在數據庫優先模式下使用實體框架。 我有一個存儲在稱為“ DomainEntities”的表中的層次結構層次結構。
當我使用實體框架生成架構時,我得到了正確的mappongs,如下所示。
現在我想知道使用該模型執行插入的方式是什么。 如果我想與某個父項插入一個新條目,我需要做所有這一切:
[HttpPost]
public ActionResult Create(DomainEntity i_EntityToCreate, int ParentEntityID)
{
using (var db = new CamelotShiftManagementEntities())
{
var parentEntity = db.DomainEntities.Find(ParentEntityID);
i_EntityToCreate.ParentEntity = parentEntity;
i_EntityToCreate.EntityTypeID = 1;
db.DomainEntities.Add(i_EntityToCreate);
db.SaveChanges();
}
return RedirectToAction("Index");
}
這是正確的還是我應該遵循另一種設計來使用實體框架表示實體的層次結構?
無需查找ParentEntity,就可以像這樣直接將DomainEntity對象與DomainEntity對象一起使用。要獲取模型中的外鍵列,請在將表導入到EDMX中時勾選“在模型中包括外鍵列”選項。
之后,使用下面的代碼:
[HttpPost]
public ActionResult Create(DomainEntity i_EntityToCreate, int? ParentEntityID)
{
using (var db = new CamelotShiftManagementEntities())
{
i_EntityToCreate.ParentEntityId = ParentEntityID;
i_EntityToCreate.EntityTypeID = 1;
db.DomainEntities.Add(i_EntityToCreate);
db.SaveChanges();
}
return RedirectToAction("Index");
}
如果ParentEntityID不為null,則刪除? 標記,使其變為不可為null的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.