Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 具有相同密钥错误的多个对象_Asp.net Mvc_Entity Framework_Object_Model_Dbcontext - Fatal编程技术网

Asp.net mvc 具有相同密钥错误的多个对象

Asp.net mvc 具有相同密钥错误的多个对象,asp.net-mvc,entity-framework,object,model,dbcontext,Asp.net Mvc,Entity Framework,Object,Model,Dbcontext,嗨,我在更新记录时遇到以下错误 ObjectStateManager中已存在具有相同密钥的对象。 ObjectStateManager无法跟踪具有相同属性的多个对象 钥匙 这是我的编辑帖子操作 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Id,Name,Type,Weightage,Description,ParentId")] HiringFactor h

嗨,我在更新记录时遇到以下错误

ObjectStateManager中已存在具有相同密钥的对象。 ObjectStateManager无法跟踪具有相同属性的多个对象 钥匙

这是我的编辑帖子操作

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id,Name,Type,Weightage,Description,ParentId")] HiringFactor hiringfactor)
    {
        if (ModelState.IsValid)
        {
            var childCount = 0;
            var indent = "";
            var parentId = hiringfactor.ParentId;

            HiringFactor parentFactor = db.HiringFactors.Find(parentId);
            if (parentFactor != null)
            {
                childCount = parentFactor.ChildHiringFactors.Count;
                indent = parentFactor.Indent + "." + (childCount + 1);
            }
            else
            {
                var parentCount = db.HiringFactors.Count(hf => (hf.ParentId == null || hf.ParentId == 0));
                indent = (parentCount + 1).ToString();
            }
            hiringfactor.Indent = indent;

            db.Entry(hiringfactor).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.ParentFactors = new SelectList(db.HiringFactors, "Id", "IndentName", hiringfactor.ParentId);
        return View(hiringfactor);
    }

是因为我在DB上下文中处理相同类型的对象吗?

问题似乎源于EntityState。在SaveChanges方法之前修改,假设hiringfactor是作为修改目标的新实体:

db.Entry(hiringfactor).State = EntityState.Modified;
按照惯例,一旦实体已由相同的键值加载,就不能重新附着模型。在保存更改之前尝试使用以下代码:

设置修改实体的另一种方法是在执行以下查找方法时使用:

HiringFactor parentFactor = db.HiringFactors.AsNoTracking().Find(parentId);
类似问题:

var parentFactor=db.HiringFactors.AsNoTracking.FirstOrDefaulthf=>hf.Id==parentId;这对我有用。谢谢你@tetsuya yamamoto
HiringFactor parentFactor = db.HiringFactors.AsNoTracking().Find(parentId);