Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.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
C# 添加行然后使用EF更新行时出错_C#_Asp.net_Asp.net Mvc 3_Entity Framework - Fatal编程技术网

C# 添加行然后使用EF更新行时出错

C# 添加行然后使用EF更新行时出错,c#,asp.net,asp.net-mvc-3,entity-framework,C#,Asp.net,Asp.net Mvc 3,Entity Framework,目前,我正试图通过AJAX向数据库表中添加一个新行,这很好。但是当我尝试更新一个不同的表时,我得到了一个错误。这是我的代码和我遇到的错误 错误 无法附加该对象,因为它已在对象上下文中。对象只有在处于未更改状态时才能重新附着 第41行:_db.ChampionCounters.连接(champion) 代码 总结 上面的代码来自处理Ajax post的控制器。就像我说的userVoteLink表创建的记录很好。但是,当我尝试更新其他表ChampionCounters时,会抛出错误 提前谢谢 您不需

目前,我正试图通过AJAX向数据库表中添加一个新行,这很好。但是当我尝试更新一个不同的表时,我得到了一个错误。这是我的代码和我遇到的错误

错误 无法附加该对象,因为它已在对象上下文中。对象只有在处于未更改状态时才能重新附着

第41行:_db.ChampionCounters.连接(champion)

代码 总结 上面的代码来自处理Ajax post的控制器。就像我说的userVoteLink表创建的记录很好。但是,当我尝试更新其他表ChampionCounters时,会抛出错误


提前谢谢

您不需要附加实例,因为上下文已经在跟踪该实例。只需删除
\u db.ChampionCounters.Attach(champion)行。

您不需要附加实例,因为上下文已经在跟踪该实例。只需删除
\u db.ChampionCounters.Attach(champion)

[HttpPost]
    public ActionResult VoteYes(int id)
    {
        string results;

        if (Request.IsAuthenticated)
        {
            var checkFirst =
                from c in _db.UserCounterLinks
                where c.counterId == id && c.userName == User.Identity.Name
                select c;

            if (checkFirst.Any())
            {
                results = "You have already voted on this counter.";
                return Json(results);
            }

            var userVoteLink = new UserCounterLink { counterId = id, userName = User.Identity.Name, userAgree = true };

            _db.UserCounterLinks.AddObject(userVoteLink);


            var champion = _db.ChampionCounters.SingleOrDefault(c => c.id == id);

            if (champion != null)
            {
                champion.positiveVotes++;
                _db.ChampionCounters.Attach(champion);
            }
            _db.SaveChanges();
            results = "Voted";
        } else
        {
            results = "You must be logged in to vote.";
        }

        return Json(results);
    }