0

I have a process that creates an object that is responsible for inserting into header /detail records. If I run the code to insert into the table on its own, every thing runs fine. However, when I call that code as a separate class within a loop I get an exception:

System.Data.Entity.Infrastructure.DbUpdateException was unhandled
Message=The INSERT statement conflicted with the FOREIGN KEY constraint "FK_CAS_ClaimsAdjustment_Header835". The conflict occurred in database "ERA835DB", table "dbo.Header835", column 'TRANSACTIONID'.

The TRANSACTIONID Column in the Header table is set as Identity=True. The child table, CAS_ClaimsAdjustment has a column TransactionID that is FK to Header.TransactionID.

Why does DBContext.SaveChanges() seem to behave differently depending on how the same code is called?

 foreach (var file in Files)
  { 
          Parser parser = new Parser();
          parser.HandleFile(file);
  }


public class Parser
{

  public void HandleFile(string file)
  {
      using (Model.DbContext dbcontext)
    {
        foreach (var itemn in file)
        {
           Claims claim = new Claims();

            // ...

           dbcontext.Claims.Add(claim);
        }

        dbcontext.SaveChanges();

    }
  }


}
Dylan
  • 165
  • 2
  • 16
  • Please show the two code snippets calling `SaveChanges()`. Hard to tell otherwise. – Gert Arnold Jan 01 '13 at 15:25
  • I have added a code snippet. The class Parser was at one time a stand alone console application. When the code was run it would each time insert a new record with no problem. – Dylan Jan 02 '13 at 19:08
  • But this does not show how the two situations are different wrt inserting header/detail records. – Gert Arnold Jan 03 '13 at 17:49
  • Hi Gert, Your right. In preparing the code snippet I realized why I was having trouble. When my code was in a console application I was using "static" keyword before my entities. I removed this and now it works fine. Thanks for your help. – Dylan Jan 04 '13 at 15:12

1 Answers1

0

I solved my problem. In my console application I was declaring my entities as "static". Of course this did not work. Once I removed the static keyword everything was fine.

Dylan
  • 165
  • 2
  • 16