简体   繁体   English

在实体框架中创建新实体时违反唯一约束

[英]Violation of Unique Constraint when creating new entity in Entity Framework

I have, errr had a working wpf application that manipulates database info (using Entity Framework, database first). 我有一个errr,它有一个可运行的wpf应用程序,用于处理数据库信息(使用Entity Framework,首先使用数据库)。

The structure of the data is 4 tables of finance info (all 1:1 mapped to the main table of the 5), with a couple of lookup tables with foreign key refs in the main table. 数据的结构是4个财务信息表(所有1:1映射到5个表中的主表),在主表中有几个带有外键引用的查找表。

I added a table (another 1:1 mapping to the main table) in SqlServer and then ran the 'Update Model from Database...' wizard to add the new table to the model. 我在SqlServer中添加了一个表(另一个与主表的1:1映射),然后运行“从数据库中更新模型...”向导,将新表添加到模型中。 Everything looks alright in the .edmx file, including the '0..1' relationship link. 在.edmx文件中,一切都看起来不错,包括“ 0..1”关系链接。

However, when I try to save, I am receiving a 'Violation of Unique Constraint' error. 但是,当我尝试保存时,收到“违反唯一约束”错误。

My creation code: 我的创建代码:

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");
  }
}

Prior to adding the new table, the above code was working. 在添加新表之前,以上代码已正常工作。 The only change was the addition of the lines: 唯一的变化是增加了以下行:

StatementsSurplusDeficit newSurplusDeficit = 
    StatementsSurplusDeficit.CreateStatementsSurplusDeficit(newStatement.StatementsMainID);
...
lGFinanceEntities.StatementsMains.Context.AddObject("StatementsSurplusDeficit", 
    newSurplusDeficit);

Interestingly, something is creating a record somewhere, because when I check SqlServer I do have new records for the 5 tables. 有趣的是, 一些地方是创造一个纪录,因为当我检查的SqlServer我对5台新记录。 Also interestingly, each time I try something and run the method, the primary key has been incremented by 2. It looks like the same record is being added twice, but I can't work out how. 同样有趣的是,每次我尝试执行某种方法并运行该方法时,主键都增加了2。看起来同一记录被添加了两次,但是我无法解决。

Edit: Following a comment suggestion, I changed the 'AddNewStatementsQuery' so lines that looked like: 编辑:根据评论建议,我更改了“ AddNewStatementsQuery”,使行如下所示:

lGFinanceEntities.StatementsMains.Context.AddObject("StatementsMains", newStatement);

were changed to: 改为:

lGFinanceEntities.StatementsMains.AddObject(newStatement);

and then to: 然后:

lGFinanceEntities.AddObject("StatementsMains", newStatement);

This did not solve the key violation error. 这不能解决密钥冲突错误。

How do I find out where/how the data is being saved twice (ie, other than lGFinanceEntities.SaveChanges() in the if statement)? 如何查找两次将数据保存在何处/如何保存(即,if语句中的lGFinanceEntities.SaveChanges()除外)?

Hmm. Looking at your code, I can see it being simplified down to: 查看您的代码,我可以看到它已简化为:

// Create the new objects    
var statement = new StatementsMain()
{
    this.LocalGovt.StakeholderID, 161, this.Year.FinancialYearID
};

var income = new StatementsIncome()
{
    StatementsMain = statement
};

var note = new StatementsNote()
{
    StatementsMain = statement
};

var rss = new StatementsRSSFinPos()
{
    StatementsMain = statement
};

var surplus = new StatementsSurplusDeficit()
{
    StatementsMain = statement
};


// Add the objects into the context 
lGFinancialEntities.AddObject(statement);
lGFinancialEntities.AddObject(income);
lGFinancialEntities.AddObject(note);
lGFinancialEntities.AddObject(rss);
lGFinancialEntities.AddObject(surplus);

// Persist the objects to the data storage
lGFinancialEntities.SaveChanges();

Or, even better: 或者,甚至更好:

// Create the main object
var statement = new StatementsMain()
{
    this.LocalGovt.StakeholderID, 161, this.Year.FinancialYearID
};

// Add the objects into the context
lGFinancialEntities.AddObject(statement);
lGFinancialEntities.AddObject(new StatementsIncome() { StatementsMain = statement });
lGFinancialEntities.AddObject(new StatementsNote() { StatementsMain = statement });
lGFinancialEntities.AddObject(new StatementsRSSFinPos() { StatementsMain = statement });
lGFinancialEntities.AddObject(new StatementsSurplusDeficit() { StatementsMain = statement });

// Persist the objects to the data storage
lGFinancialEntities.SaveChanges();

But, this tells me there is a lot about your data schema that's not obvious here. 但是,这告诉我关于您的数据模式的很多事情在这里并不明显。 For instance, what does the value 161 reference in the StatementsMain object? 例如,在StatementsMain对象中值161引用了什么?

FYI, assigning the primary object to the objects in which it is a foreign-key lets EF do the work of assigning the new ID to the other objects as they are persisted. 仅供参考,将主要对象分配给其中是外键的对象使EF能够在持久化其他对象时为其他对象分配新ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM