嘿,我正在尝试使用DB第一模式中的实体框架。 我有一个Enitties层次结构,存储在一个名为" DomainEntities"的表中。
当我使用实体框架生成模式时,我得到了正确的mappong,看起来像这样。
现在我想知道我应该使用这个模型执行插入的方式是什么。 如果我想插入一个新的条目与某个父母,我需要做所有这些:
[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");
}
这是正确的还是我应该遵循另一种设计来表示使用实体框架的实体层次结构?
答案 0 :(得分:1)
没有必要找到ParentEntity,您可以直接使用ParentEntityID和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,则删除?标记,使其成为不可空的类型。