EF架构~CodeFirst自关联表的插入

回到目录

这个文章对之前EF的一个补充,对于一些自关联表的添加,如果你建立了表约束确实有这种问题,一般主键为整形自增,父ID为可空,这时,在添加时如果不为ID赋值,结果就会出错。

错误:

无法确定依赖操作的有效顺序。由于外键约束、模型要求或存储生成的值,因此可能存在依赖关系。

解决:

  [HttpPost]
        public ActionResult Create(WebManageMenus entity)
        {
            try
            {
                entity.Id = -1;//自关联表要主动赋值
                entity.About = "";
                entity.Operator = "";
                menuRepository.Insert(entity);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

结果:

回到目录

原文地址:https://www.cnblogs.com/lori/p/5319511.html