【发布时间】:2013-01-22 08:12:17
【问题描述】:
我有,errr 有一个操作数据库信息的工作 wpf 应用程序(使用实体框架,数据库优先)。
数据的结构是 4 个财务信息表(全部 1:1 映射到 5 个主表),主表中有几个带有外键引用的查找表。
我在 SqlServer 中添加了一个表(另一个 1:1 映射到主表),然后运行“从数据库更新模型...”向导将新表添加到模型中。 .edmx 文件中的一切看起来都很好,包括“0..1”关系链接。
但是,当我尝试保存时,我收到“违反唯一约束”错误。
我的创建代码:
private void AddNewStatementsQuery(LGFinanceEntities lGFinanceEntities)
{
StatementsMain newStatement = StatementsMain.CreateStatementsMain(9999, this.LocalGovt.StakeholderID, 161, this.Year.FinancialYearID);
StatementsIncome newInc = StatementsIncome.CreateStatementsIncome(newStatement.StatementsMainID);
StatementsNote newNote = StatementsNote.CreateStatementsNote(newStatement.StatementsMainID);
StatementsRSSFinPos newRSSFinPos = StatementsRSSFinPos.CreateStatementsRSSFinPos(newStatement.StatementsMainID);
StatementsSurplusDeficit newSurplusDeficit = StatementsSurplusDeficit.CreateStatementsSurplusDeficit(newStatement.StatementsMainID);
lGFinanceEntities.StatementsMains.Context.AddObject("StatementsMains", newStatement);
lGFinanceEntities.StatementsMains.Context.AddObject("StatementsIncomes", newInc);
lGFinanceEntities.StatementsMains.Context.AddObject("StatementsNotes", newNote);
lGFinanceEntities.StatementsMains.Context.AddObject("StatementsRSSFinPos", newRSSFinPos);
lGFinanceEntities.StatementsMains.Context.AddObject("StatementsSurplusDeficit", newSurplusDeficit);
if (lGFinanceEntities.SaveChanges() != 1) // this is causing the exception
{
MessageBox.Show("Error. New Statements not created", "Database Error");
}
}
在添加新表之前,上面的代码正在运行。唯一的变化是添加了以下几行:
StatementsSurplusDeficit newSurplusDeficit =
StatementsSurplusDeficit.CreateStatementsSurplusDeficit(newStatement.StatementsMainID);
...
lGFinanceEntities.StatementsMains.Context.AddObject("StatementsSurplusDeficit",
newSurplusDeficit);
有趣的是,something 正在某处创建记录,因为当我检查 SqlServer 时,我确实有 5 个表的新记录。同样有趣的是,每次我尝试某些东西并运行该方法时,主键都会增加 2。看起来同一条记录被添加了两次,但我不知道如何。
编辑: 根据评论建议,我更改了“AddNewStatementsQuery”,如下所示:
lGFinanceEntities.StatementsMains.Context.AddObject("StatementsMains", newStatement);
改为:
lGFinanceEntities.StatementsMains.AddObject(newStatement);
然后到:
lGFinanceEntities.AddObject("StatementsMains", newStatement);
这并没有解决密钥冲突错误。
我如何找出数据被保存两次的位置/方式(即除了 if 语句中的lGFinanceEntities.SaveChanges())?
【问题讨论】:
-
您是否有理由通过
Context属性添加项目?您可以将它们直接添加到DbContext(lGFinanceEntities) 或表本身(StatementMains等)。 -
可能是因为我遵循的网站/教程就是这样做的。将考虑通过您建议的不同方法添加
-
@TiesonT。嗨,没有添加到上下文或表格似乎对结果没有任何影响。仍然是唯一的密钥违规
-
你能做类似
newInc.StatementsMain = newStatement(4 次)的事情并且只将newStatement对象添加到上下文中吗?
标签: c# .net wpf entity-framework