【问题标题】:Error while adding a row and then updating a row using EF添加行然后使用 EF 更新行时出错
【发布时间】:2012-07-15 01:34:35
【问题描述】:

目前我正在尝试通过 AJAX 向数据库表中添加一个新行,这工作正常。但后来我尝试更新另一个表,但出现错误。这是我的代码和我遇到的错误。

错误

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

第 41 行:_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);
    }

总结

上面的代码来自处理 Ajax 帖子的控制器。就像我说的 userVoteLink 表创建一个记录就好了。但是当我尝试更新另一个表 ChampionCounters 时,就会抛出错误。

提前致谢!

【问题讨论】:

    标签: c# asp.net asp.net-mvc-3 entity-framework


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多