gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:37:34 25 4
gpt4 key购买 nike

编辑:如果有人想知道,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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com