简体   繁体   English

向EF添加新实体时出错:发生了参照完整性约束违规

[英]Error when adding new entity to EF : A referential integrity constraint violation occurred

I'm adding a new entity that is built through an external class and I get this error : A referential integrity constraint violation occurred: A primary key property that is a part of referential integrity constraint cannot be changed when the dependent object is Unchanged unless it is being set to the association's principal object. The principal object must be tracked and not marked for deletion. 我正在添加一个通过外部类构建的新实体,我收到此错误: A referential integrity constraint violation occurred: A primary key property that is a part of referential integrity constraint cannot be changed when the dependent object is Unchanged unless it is being set to the association's principal object. The principal object must be tracked and not marked for deletion. A referential integrity constraint violation occurred: A primary key property that is a part of referential integrity constraint cannot be changed when the dependent object is Unchanged unless it is being set to the association's principal object. The principal object must be tracked and not marked for deletion. :

Edit : The ReconFact entity is not linked to any other entities 编辑ReconFact实体未链接到任何其他实体

The code ( edited ) : 代码(已编辑 ):

// the context class
AccountingModelContext db = new AccountingModelContext();
// query some data
List<Reconciliation> recon = db.Reconciliations
        .Where(r => r.ReconNum == 112293)  // scenario 18 
        .Include(r => r.ReconciliationDetails.Select(rd => rd.JrnlEntryDetail).Select(jd => jd.JrnlEntry).Select(j => j.ARInvoices.Select(i => i.ARInvoiceDetails)))
        .Include(r => r.ReconciliationDetails.Select(rd => rd.JrnlEntryDetail).Select(jd => jd.JrnlEntry).Select(j => j.ARCredMemoes.Select(c => c.ARCredMemoDetails)))
        .ToList();
// class that will manager business logic and generate facts with above data
ReconFactGenerator generator = new ReconFactGenerator(recon);
// call to the method that will return a list of facts
List<ReconFact> scenario18 = generator.GenerateFacts();
// ERROR RAISED HERE
scenario18.ForEach(f => db.ReconFacts.Add(f));
// never reached
db.SaveChanges();

It's very basic I build a list of ReconFact entities with ReconFactGenerator class. 这是非常基本的我使用ReconFactGenerator类构建ReconFact实体列表。 No ID's are specified as they are new entities. 没有指定ID,因为它们是新实体。

edited It works perfectly if I create a new entity in the same method like here Before I query data from the context : 编辑如果我在这里使用相同的方法创建一个新实体,那么它是完美的。在我从上下文查询数据之前:

ReconFact testfact = new ReconFact { ItemCode = "test", ReconNum = 1234, ReconDate = DateTime.Parse("2099-01-01"), ShortName = "L_SZTREDFD", InvoiceAmount = 0, CredMemoAmount = 0, IncomingPayAmount = 0, OutgoingPayAmount = 0, JrnlEntryAmount = 0, OtherAmount = 0 };
db.ReconFacts.Add(testfact); // no problems no error raised
db.SaveChanges(); // I can see the new record in my database 
                  // the ID was generated successfully 
                  // as I've specified identity(1,1) in the database

Added Edit 2 After I query data from the context like this : 添加编辑2在我从上下文查询数据后,如下所示:

 List<Reconciliation> recon = db.Reconciliations
        .Where(r => r.ReconNum == 112293)  // scenario 18 
        .Include(r => r.ReconciliationDetails.Select(rd => rd.JrnlEntryDetail).Select(jd => jd.JrnlEntry).Select(j => j.ARInvoices.Select(i => i.ARInvoiceDetails)))
        .Include(r => r.ReconciliationDetails.Select(rd => rd.JrnlEntryDetail).Select(jd => jd.JrnlEntry).Select(j => j.ARCredMemoes.Select(c => c.ARCredMemoDetails)))
        .ToList();

The context is not able to save anymore returning the above error. 上下文无法再保存以返回上述错误。

edited Why is an error raised when I want to save after I query the context and raises no error before ? 编辑为什么在查询上下文后我想保存时出现错误并且之前没有引发错误?

Found out how to get around though it doesn't explain why the error occurs : 找到了解决方法虽然它无法解释错误发生的原因:

// the context class
AccountingModelContext db = new AccountingModelContext();
// query some data
List<Reconciliation> recon = db.Reconciliations
        .Where(r => r.ReconNum == 112293)  // scenario 18 
        .Include(r => r.ReconciliationDetails.Select(rd => rd.JrnlEntryDetail).Select(jd => jd.JrnlEntry).Select(j => j.ARInvoices.Select(i => i.ARInvoiceDetails)))
        .Include(r => r.ReconciliationDetails.Select(rd => rd.JrnlEntryDetail).Select(jd => jd.JrnlEntry).Select(j => j.ARCredMemoes.Select(c => c.ARCredMemoDetails)))
        .ToList();
// class that will manager business logic and generate facts with above data
ReconFactGenerator generator = new ReconFactGenerator(recon);
// call to the method that will return a list of facts
List<ReconFact> scenario18 = generator.GenerateFacts();

// ERROR RAISED HERE
// scenario18.ForEach(f => db.ReconFacts.Add(f));

// INSTEAD OF REUSING THE CONTEXT I CREATE A NEW ONE PROBLEM SOLVED !
using (db = new AccountingModelContext())
{
  scenario18.ForEach(f => db.ReconFacts.Add(f));
  db.SaveChanges();
}
db.SaveChanges();

Out of interest, do you get the same issue when you replace the List<T>.ForEach() with an actual ForEach , so change: 出于兴趣,当您使用实际ForEach替换List<T>.ForEach()时,是否会遇到相同的问题,因此请更改:

scenario18.ForEach(f => db.ReconFacts.Add(f));

To: 至:

foreach(var f in scenario18)
{
  db.ReconFacts.Add(f);
}

db.SaveChanges();

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

相关问题 发生参照完整性约束冲突。 更新EF时 - A referential integrity constraint violation occurred. When Updating EF 尝试在Entity Framework中进行更新时出现错误“发生了引用完整性约束冲突” - Error “A referential integrity constraint violation occurred” when trying update in Entity Framework 错误“发生了参照完整性约束冲突” - Error “A referential integrity constraint violation occurred” 发生了参照完整性约束违规 - A referential integrity constraint violation occurred 发生参照完整性约束违规 - Referential integrity constraint violation occurred 发生参照完整性约束冲突 Nullable FK - A referential integrity constraint violation occurred Nullable FK EF 6 Code First,使用包含在导航属性上的外键ID更改会导致“发生引用完整性约束违规”错误 - EF 6 Code First, changing a Foreign Key Id with an Include on navigation property causes “A referential integrity constraint violation occurred” error 实体框架迁移-违反参照完整性约束 - Entity Framework Migrations - A referential integrity constraint violation 实体框架:对多对多关系的参照完整性约束违反 - Entity Framework: A referential integrity constraint violation on many to many relationship 尝试将FK设置为​​null时,引用完整性约束违规 - Referential Integrity Constraint violation when attempting to set a FK to null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM