0

I would like to insert two records into two tables where result of first insert needs the second insert. Now it not working correctly because it return SQL exception with foreign key.

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_VacancyLog_Vacancy". The conflict occurred in database "mydb", table "dbo.Vacation", column 'Id'. The statement has been terminated.

How to fix it?

using (var transaction = this.Context.Database.BeginTransaction())
{
    var result = this.Context.Vacancy.Add(vacancy);
    this.Context.SaveChanges();

    var vacancyLog = new VacancyLog()
    {
        Status = 1,
        ModificationDate = DateTime.Now(),
        VacancyId = result.Id
    };
    this.Context.VacancyLog.Add(vacancyLog);
    this.Context.SaveChanges();

    transaction.Commit();
}
Luki
  • 437
  • 2
  • 6
  • 15
  • How is your solution "not working correctly"? Are you experiencing an error? Does it work but the records are missing? Is `result.Id` equal to `0`? We can't help you without knowing the details. – JuanR May 25 '23 at 16:26

0 Answers0