c# - DeleteOnSubmit LINQ 异常 "Cannot add an entity with a key that is already in use"

标签 c# linq

编辑:如果有人想知道,actionhandler 会调用创建和处理相同类型数据上下文的代码,以防可能与此行为有任何关系。该代码没有触及 MatchUpdateQueue 表,但我认为我应该提及它以防万一。

双重编辑:每个回答正确的人!我把答案给了遭受我最多提问的受访者。解决这个问题导致另一个问题(隐藏在处理程序中)弹出,它恰好抛出完全相同的异常。哎呀!

我在删除 LINQ 中的项目时遇到了一些问题。下面代码中的 DeleteOnSubmit 调用导致 LINQ 异常并显示消息“无法添加具有已在使用的 key 的实体。”我不确定我在这里做错了什么,它开始让我陷入困境。主键只是一个整数自动增量列,在我尝试从数据库队列中删除一个项目之前我没有其他问题。希望我在这里做的事情很容易被不是我的人发现!

static void Pacman()
{
    Queue<MatchUpdateQueue> waiting = new Queue<MatchUpdateQueue>();

    events.WriteEntry("matchqueue worker thread started");

    while (!stop)
    {
        if (waiting.Count == 0)
        {
            /* grab any new items available */
            aDataContext db = new aDataContext();
            List<MatchUpdateQueue> freshitems = db.MatchUpdateQueues.OrderBy(item => item.id).ToList();

            foreach (MatchUpdateQueue item in freshitems)
                waiting.Enqueue(item);
            db.Dispose();
        }
        else
        {
            /* grab & dispatch waiting item */
            MatchUpdateQueue item = waiting.Peek();
            try
            {
                int result = ActionHandler.Handle(item);
                if (result == -1)
                    events.WriteEntry("unknown command consumed : " + item.actiontype.ToString(), EventLogEntryType.Error);

                /* remove item from queue */
                waiting.Dequeue();

                /* remove item from database */
                aDataContext db = new aDataContext();
                db.MatchUpdateQueues.DeleteOnSubmit(db.MatchUpdateQueues.Single(i => i == item));
                db.SubmitChanges();
                db.Dispose();
            }
            catch (Exception ex)
            {
                events.WriteEntry("exception while handling item : " + ex.Message, EventLogEntryType.Error);
                stop = true;
            }
        }

        /* to avoid hammering database when there's nothing to do */
        if (waiting.Count == 0)
            Thread.Sleep(TimeSpan.FromSeconds(10));
    }

    events.WriteEntry("matchqueue worker thread halted");
}

最佳答案

你可以做一些事情

db.MatchUpdateQueues.DeleteOnSubmit(db.MatchUpdateQueues.Single(theItem => theItem == item));

只是一个注释,因为其他答案暗示了 Attach..除非实体已经序列化,否则您将无法在除接收项目的原始上下文之外的上下文中使用附加。

关于c# - DeleteOnSubmit LINQ 异常 "Cannot add an entity with a key that is already in use",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/682890/

相关文章:

javascript - 为什么我的 blazor.server.js 之后无法加载任何 js?

.net - 使用 LINQ 从列表创建元组列表

XML 的 C# LINQ 左外连接无法正常工作

c# - LINQ - 当值为 NULL 时排除过滤器

c# - LINQ 中枚举器的奇怪行为

c# - 使用 Razor 按表中的日期对模型元素进行分组

c# - 如何在 C# 中枚举系统上所有打开的文件?

c# - LINQ 和 AutoMapper

c# - 在共享主机上使用 SQL Server 数据库

c# - 如何强制 Linq 更新一行的上次编辑时间?